Convert Binary Number in a Linked List to Integer这道题在leetcode上面算做是“easy”,然而小生我仍是不会作,因而根据大佬的回答来整理一下思路以便往后复习。node
https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/算法
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.编程
翻译:Head是一个单链表的引用,每一个链表的元素都是1或者0,链表的数字们组成起来表明一个二进制数字(好比说 [1,0,1]表明二进制的101)。你须要返回这个二进制所表明的十进制数字。编程语言
输入输出:spa
Input: head = [1,0,1] .net
Output: 5翻译
这是单链表的定义:code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/blog
首先做为算法题,大多数语言均可以用,做者这里习惯,用的是C++。ci
这道题考验的主要是答题者对编程语言中二进制的了解。
二进制的101表明十进制的5,这是由于 4 + 1 = 5。这个不用说了吧。
而咱们要注意的就是 “<<”,这个不是咱们熟知的C++输出符,而是指往左移,后面的数字是指左移1一位。假设ret是3,ret <<= 1 以后就会ret = 6。
|= 意思为:按位或后赋值,也就是给对应的二进制的数字的位置赋值,假设ret是7,ret |= 4以后ret仍然是7,由于7是0111,4是0100,注意这4这个位置已经有1了因此已经赋值了,所以结果不变。
head->val就是指链表里面的val。关于链表的定义能够参考:https://blog.csdn.net/slandarer/article/details/91863177
解题思路见注释,很是通俗易懂。
参考答案:
class Solution {
public:
int getDecimalValue(ListNode* head) {
int ret = 0; //设置ret为0。
while(head) //在head都不为NULL的状况下继续循环
{
ret <<= 1;
//咱们会把ret左移,因此说若是以前已经有一位1了.
//那就会被推到更高的位置,好比说以前为0001,那么如今就是0010
ret |= head->val;
//若是head->val是1,就给这一层赋值1,若是是0,就维持不变。
//例子:好比说以前咱们已经获得了0010,如今若是为1,就是0011;若是是0,就是0010不变。
head = head->next;
//指向下一个链表元素。
}
return ret;
}
};