-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertBinaryNumberInALinkedListToInteger.java
More file actions
42 lines (34 loc) · 1.08 KB
/
ConvertBinaryNumberInALinkedListToInteger.java
File metadata and controls
42 lines (34 loc) · 1.08 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
41
42
package com.company;
import java.util.LinkedList;
//1290. Convert Binary Number in a Linked List to Integer
public class ConvertBinaryNumberInALinkedListToInteger {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public static void main(String[] args) throws Exception {
ListNode listNode = new ListNode(1);
ListNode listNode1 = new ListNode(0);
ListNode listNode2 = new ListNode(1);
listNode.next = listNode1;
listNode1.next = listNode2;
System.out.println("result " + getDecimalValue(listNode));
}
public static int getDecimalValue(ListNode head) {
LinkedList<Integer> linkedList = new LinkedList<>();
while (head != null) {
linkedList.add(head.val);
head = head.next;
}
int count = 0;
int result = 0;
for (int i = linkedList.size() - 1; i >= 0; --i) {
result += (linkedList.get(i) * Math.pow(2, count));
count++;
}
return result;
}
}