示例 1:

示例 2:
示例 3:
示例 4:
示例 5:
5 / 2 = 2 余 1
2 / 2 = 1 余 0
1 / 2 = 0 余 1
得到二进制数101,如果要得到原始十进制数,只需要反推即可:商 * 2(除数) + 余数:
0 * 2 + 1 = 1
1 * 2 + 0 = 2
2 * 2 + 1 = 5
这样就可以得到二进制数对应的十进制数
package LinkedList;/*** @Author: IronmanJay* @Description: 1290.二进制链表转整数* @CreateTime: 2022-12-06 13:10*/
public class p1290_ConvertBinaryNumberInALinkedListToInteger {int val;p1290_ConvertBinaryNumberInALinkedListToInteger next;public p1290_ConvertBinaryNumberInALinkedListToInteger(int val) {this.val = val;}public p1290_ConvertBinaryNumberInALinkedListToInteger(int val, p1290_ConvertBinaryNumberInALinkedListToInteger next) {this.val = val;this.next = next;}public static void main(String[] args) {p1290_ConvertBinaryNumberInALinkedListToInteger node1 = new p1290_ConvertBinaryNumberInALinkedListToInteger(1);p1290_ConvertBinaryNumberInALinkedListToInteger node2 = new p1290_ConvertBinaryNumberInALinkedListToInteger(0);p1290_ConvertBinaryNumberInALinkedListToInteger node3 = new p1290_ConvertBinaryNumberInALinkedListToInteger(1);node1.next = node2;node2.next = node3;int res = getDecimalValue(node1);System.out.println("res = " + res);}public static int getDecimalValue(p1290_ConvertBinaryNumberInALinkedListToInteger head) {p1290_ConvertBinaryNumberInALinkedListToInteger p = head;int res = 0;while (p != null) {res = res * 2 + p.val;p = p.next;}return res;}}
#includestruct ListNode
{int val;struct ListNode *next;
};int getDecimalValue(struct ListNode* head)
{struct ListNode* p = head;int res = 0;while (p != NULL){res = res * 2 + p->val;p = p->next;}return res;
}/*主函数省略*/
Java语言版

C语言版
