-
1290. Convert Binary Number in a Linked List to Integer javaLeetCode_Study_Plan/Programming Skills 2022. 9. 24. 13:09
https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/
Convert Binary Number in a Linked List to Integer - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public int getDecimalValue(ListNode head) { StringBuilder stringBuilder = new StringBuilder(); while (head != null) { stringBuilder.append(head.val); head = head.next; } return Integer.valueOf(stringBuilder.toString(), 2); } }
아래는 다른 방법이 없나 찾아본 풀이이다.
for 문을 저렇게 사용할 수도 있어 참신했다.
class Solution { public int getDecimalValue(ListNode head) { int ans = 0; for (; head != null; head = head.next) ans = ans * 2 + head.val; return ans; } }
'LeetCode_Study_Plan > Programming Skills' 카테고리의 다른 글
104. Maximum Depth of Binary Tree java (0) 2022.09.24 876. Middle of the Linked List java (0) 2022.09.24 953. Verifying an Alien Dictionary java (0) 2022.09.22 1309. Decrypt String from Alphabet to Integer Mapping java (0) 2022.09.22 709. To Lower Case java (0) 2022.09.22