关注 每天一道编程题 专栏,一起学习进步。
题目
Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.
Return the decimal value of the number in the linked list.
Example 1:
Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 = (5) in base 10
Example 2:
Input: head = [0]
Output: 0
Example 3:
Input: head = [1]
Output: 1
Example 4:
Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0]
Output: 18880
Example 5:
Input: head = [0,0]
Output: 0
Constraints:
The Linked List is not empty.
Number of nodes will not exceed 30.
Each node's value is either 0 or 1.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
分析
题意:给出一个二进制单链表,输出十进制值。
根据二进制转十进制的方法,101=1<<2+0<<1+1<<0. (<<n 左移运算,相当于乘n次2)
因此需要知道最高位对应的n是几
显然不太好做。
可以使用递归,先递归到最深处(最后一位),然后开始出栈,每出一次,让n++;
解答
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
int n=-1;
int res=0;
public int getDecimalValue(ListNode head) {
if(head.next!=null){
getDecimalValue(head.next);
}
n++;
res+=head.val<<n;
return res;
}
}
评论区其他答案
public int getDecimalValue(ListNode head) {
int ans = 0;
while (head != null) {
ans = (ans << 1) | head.val;
head = head.next;
}
return ans;
}
显然这个算法更高明,没有使用递归,空间复杂度低。
原理:
<mark>前置知识:ans<<1 相当于ans*2;二进制 | 二进制相当于二进制+二进制</mark>
因此ans = (ans <<1) | head.val 类似于 ans = ans*2 +head.val
拓展:
- 二进制 | 二进制 相当于二进制+二进制
- 二进制 & 二进制 相当于二进制*二进制
(这也是为什么逻辑代数中可以用’+‘和’*'替换’或’和’与’的原因)