I, entitled 1
Second, the idea
Third, the code
public class T1290 {
public static void main(String[] args) {
// int input[] = {1,0,1}; //5
// int input[] = {0, 0}; //0
int input[] = {1,0,0,1,0,0,1,1,1,0,0,0,0,0,0}; //18880
// int input[] = {1}; //1
ListNode root = new ListNode(input[0]);
ListNode node = root;
for ( int i = 1; i < input.length; i++ ){
ListNode tmp = new ListNode(input[i]);
node.next = tmp;
node = node.next;
}
System.out.println( getDecimalValue(root));
}
public static int getDecimalValue(ListNode head) {
//方案1
/* String result = "";
ListNode next = head;
while ( next != null ){
result += next.val;
next = next.next;
}
// System.out.println( result );
// System.out.println( Integer.valueOf(result,2));
return Integer.valueOf(result,2);*/
//方案2
int result = 0;
ListNode node = head;
while ( node != null ){
result *= 2;
result += node.val;
node = node.next;
}
return result;
}
}
//Definition for singly-linked list.
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/convert-binary-number-in-a-linked-list-to-integer
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source. ↩︎