题目
给你一个单链表的引用结点 head。链表中每个结点的值不是 0 就是 1。已知此链表是一个整数数字的二进制表示形式。
请你返回该链表所表示数字的 十进制值 。
示例
输入:head = [1,0,1]
输出:5
解释:二进制数 (101) 转化为十进制数 (5)
输入:head = [0]
输出:0
输入:head = [1]
输出:1
输入:head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0]
输出:18880
输入:head = [0,0]
输出:0
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-binary-number-in-a-linked-list-to-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1
Java实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public int getDecimalValue(ListNode head) {
ListNode dummy = traverse(head);
int flag = 0;
int sum = 0;
while (dummy != null) {
sum += dummy.val * Math.pow(2, flag++);
dummy = dummy.next;
}
return sum;
}
//翻转链表
public ListNode traverse(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}