LeetCode - Algorithms - 1290. Convert Binary Number in a Linked List to Integer

Problem

1290. Convert Binary Number in a Linked List to Integer

Java

Bit Manipulation

© Approach 2: Bit Manipulation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 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) {
if (head == null)
return 0;
int d = head.val;
while (head.next != null) {
d = (d << 1) | head.next.val;
head = head.next;
}
return d;
}
}

Submission Detail

  • 102 / 102 test cases passed.
  • 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 11.21% of Java online submissions for Convert Binary Number in a Linked List to Integer.

my solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* 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 n = 0;
ListNode node = head;
while (node != null) {
n++;
node = node.next;
}
node = head;
int x = 0;
for (int i = n - 1; i > 0; i--) {
x += node.val * (2 << (i - 1));
node = node.next;
}
x += node.val;
return x;
}
}

Submission Detail

  • 102 / 102 test cases passed.
  • 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 10.97% of Java online submissions for Convert Binary Number in a Linked List to Integer.