[leetcode] 6
Leet Code 1290. Convert Binary Number in a Linked List to Integer
Problem
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
Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 = (5) in base 10
해석
node가 입력되는데 그 값을 2진수의 숫자로 생각하고 10진수로 값이 얼마인지 구하는 방법이다. 입력된 node의 val은 0,1만으로 이루어져 있고 node.next의 값은 그다음값의 reference값이 저장되어 있다.
Solution in JavaScript
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {number}
*/
var getDecimalValue = function(head) {
var result=0;
while(true){ 무한 반복
result=result*2+head.val; 결과값에 전에 갖고 있던 값을 *2를 하고 head.val값을 더한다 shift연산자가 어색해서 *2로 대체함
if(head.next==null)
return result; head.next가 null이라면 마지막 node 이기때문에 result값을 리턴한다.
head=head.next 다음 node의 reference값을 head에 대입해서 while문을 계속 실행한다.
}
};
Solution in 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) {
int result=0;
while(true){
result=2*result+head.val;
if(head.next==null){
return result;
}
head=head.next;
}
}
}