File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed
Leetcode/leetcodeTags/LinkedList Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments