1. 题目
题目链接1290. 二进制链表转整数
2. 思路
2.1 菜鸡思路
刚开始是遍历一次链表,取得链表节点的数量,然后把这个数量作为二进制转换十进制的次方数。代码如下3.1所示。
2.2 大佬思路
不用获取链表长度,在遍历的过程中计算结果,因为每次读到的一个值可以看成是二进制串的最低位,然后将原来的结果×2在加上当前值即可。
3. 代码
3.1 菜鸡思路
class Solution {
public int getDecimalValue(ListNode head) {
int len = 1;
ListNode tmp = head;
// 获取链表的节点个数
while (tmp.next != null) {
tmp = tmp.next;
len++;
}
int res = 0;
while (head != null) {
if (head.val == 1) {
// 如果是1的话就加2^(--len)
res += Math.pow(2, --len);
} else {
len--;
}
head = head.next;
}
return res;
}
}
3.2 大佬思路
class Solution {
public int getDecimalValue(ListNode head) {
int res = 0;
while (head != null) {
//左移一位相当于×2
res = (res << 1) + head.val;
head = head.next;
}
return res;
}
}