Convert Binary Number in a Linked List to Integer This question is counted in leetcode the above is "easy", but I still would not do niche, so to organize according Gangster answer some ideas for future review.
https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/
1. Original title:
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.
Translation: Head is a singly-linked list of references, each element of the list is 1 or 0, list of figures who formed it represents a binary digit (for example, [1,0,1] represent a binary 101). You need to return the binary decimal number represents.
input Output:
Input: head = [1,0,1]
Output: 5
This is the definition of a single list:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
2. Problem-solving ideas:
First, as an algorithm problem, most languages can be used, of habit here, using C ++.
This question is to test the main respondents programming language in binary understanding.
. A problem-solving knowledge needed:
101 represents a binary decimal 5, since 4 + 1 = 5. This goes without saying it.
And we should pay attention to is the "<<" This is not our well-known C ++ output operator, but rather to the left, the latter figure refers to the left by one place. Ret 3 is assumed, it will after 1 ret << = ret = 6.
| = Meaning: Bitwise or after the assignment, that is, to the position corresponding binary number assignment, assuming ret 7, ret | after 4 = ret is still 7 because 7 is 0111,4 0100, this note 4 this position has therefore been assigned a 1, so the result unchanged.
head-> val which refers to the list of val. The definition of a linked list can refer to: https://blog.csdn.net/slandarer/article/details/91863177
. B problem-solving ideas:
See note problem-solving ideas, very easy to understand.
Answer:
{Solution class
public:
int getDecimalValue (head ListNode *) {
int ret = 0; // set to 0 ret .
the while (head) // the cycle continues in the case of head not to NULL
{
ret <<= 1;
// we will ret left, so that if you already have a 1 before.
// it will be pushed to a higher position, for example, before 0001, it is now 0010
ret |= head->val;
// If the head-> val 1, give this layer assignment 1, if it is 0, it remains unchanged.
// Example: For example, before 0010 we've got now if 1 is 0011; if it is 0, 0010 is unchanged.
head = head->next;
// point to the next list element.
}
Return RET;
}
};