문제풀이 2021 03 02
2021.03.01 연습
- 사용언어 : java
/**
* 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 sb = new StringBuilder();
while (head != null) {
sb.append(head.val);
head = head.next;
}
return Integer.parseInt(sb.toString(), 2);
}
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Convert Binary Number in a Linked List to Integer. Memory Usage: 36.4 MB, less than 60.14% of Java online submissions for Convert Binary Number in a Linked List to Integer.
- 다른 코드 참고
/**
* 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) {
int val = 0;
while (head != null) {
val = (val << 1) + (head.val);
head = head.next;
}
return val;
}
}