-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryLinkedListToDecimal.java
74 lines (60 loc) · 1.88 KB
/
BinaryLinkedListToDecimal.java
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package math.easy;
import linkedlist.ListNode;
/***
* Problem 1290 in Leetcode: https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/
*
* 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.
* The most significant bit is at the head of the linked list.
*
* Example 1:
* Input: head = [1,1,0,1]
* Output: 13
*
* Example 2:
* Input: head = [1,0,1,0]
* Output: 10
*/
public class BinaryLinkedListToDecimal {
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(0);
head.next.next = new ListNode(1);
head.next.next.next = new ListNode(0);
System.out.println("Brute Force: " + convertBinaryLinkedListToDecimalBruteForce(head));
System.out.println("Bitwise: " + convertBinaryLinkedListToDecimalBitwise(head));
}
private static int convertBinaryLinkedListToDecimalBruteForce(ListNode head) {
if (head == null) {
return 0;
}
int length = 0;
ListNode temp = head;
while (temp != null) {
length++;
temp = temp.next;
}
int base = (int) Math.pow(2, length - 1);
int decimal = 0;
while (head != null) {
decimal = head.val * base + decimal;
base = base / 2;
head = head.next;
}
return decimal;
}
private static int convertBinaryLinkedListToDecimalBitwise(ListNode head) {
if (head == null) {
return 0;
}
int decimal = 0;
while (head != null) {
decimal = (decimal << 1) | head.val;
head = head.next;
}
return decimal;
}
}