LeetCode_Study_Plan/Programming Skills

1290. Convert Binary Number in a Linked List to Integer java

개발하는루루 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;
  }
}