Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b288f98

Browse files
LC#290 convert number in linkedlist nodes as whole to decimal from binary
1 parent 3816f72 commit b288f98

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package LinkedList;
2+
3+
public class ConvertBinaryNumToIntegerInLinkedList290 {
4+
5+
public class ListNode {
6+
int val;
7+
ListNode next;
8+
9+
ListNode() {
10+
}
11+
12+
ListNode(int val) {
13+
this.val = val;
14+
}
15+
16+
ListNode(int val, ListNode next) {
17+
this.val = val;
18+
this.next = next;
19+
}
20+
}
21+
22+
public int getDecimalValue(ListNode head) {
23+
24+
StringBuilder sb = new StringBuilder("");
25+
ListNode temp = head;
26+
27+
while (temp != null) {
28+
sb.append(temp.val);
29+
temp = temp.next;
30+
}
31+
32+
// long binaryValue = Long.parseLong(sb.toString());
33+
// int decimal = getDecimalFromBinary(binaryValue);
34+
35+
return Integer.parseInt(sb.toString(), 2);
36+
}
37+
38+
/*
39+
* private static int getDecimalFromBinary(Long binaryValue) { int total = 0;
40+
* int power = 0;
41+
*
42+
* while (binaryValue != 0) { long rem = binaryValue % 10; total += (rem *
43+
* Math.pow(2, power++)); binaryValue /= 10; }
44+
*
45+
* return total; }
46+
*/
47+
48+
//2nd approach
49+
public int getDecimalValue2(ListNode head) {
50+
int ans = 0;
51+
ListNode temp = head;
52+
53+
while (temp != null) {
54+
ans *= 2;
55+
ans += temp.val;
56+
temp = temp.next;
57+
}
58+
59+
return ans;
60+
}
61+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /