-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBinaryNumberToInteger.java
More file actions
40 lines (33 loc) · 1.4 KB
/
BinaryNumberToInteger.java
File metadata and controls
40 lines (33 loc) · 1.4 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
// Given head which is a reference node to a singly-linked list.
// The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.
// Return the decimal value of the number in the linked list.
// See: https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/
package leetcode.linkedlist;
import static leetcode.util.linkedlist.LinkedListUtil.initList;
import java.util.Stack;
import leetcode.util.linkedlist.ListNode;
public class BinaryNumberToInteger {
public int getDecimalValue(ListNode node) {
Stack<Integer> s = new Stack<>();
while (node != null) {
s.push(node.val);
node = node.next;
}
int result = 0;
int pow = 1;
while (!s.empty()) {
result += s.pop() * pow;
pow = pow * 2;
}
return result;
}
public static void main(String... args) {
BinaryNumberToInteger sln = new BinaryNumberToInteger();
System.out.println(sln.getDecimalValue(initList(1, 0, 1)) == 5);
System.out.println(sln.getDecimalValue(initList(0)) == 0);
System.out.println(sln.getDecimalValue(initList(1)) == 1);
System.out.println(sln.getDecimalValue(
initList(1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0)) == 18880);
System.out.println(sln.getDecimalValue(initList(0, 0)) == 0);
}
}