[리트코드] 1290. Convert Binary Number in a Linked List to Integer




1290. Convert Binary Number in a Linked List to Integer

리트코드

나의 풀이

/**
 * 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) {
    const acc = []
    let target = head
    while(1){
        acc.push(target.val)
        if(target.next)target=target.next
        else break
    }
    return parseInt(acc.join(""),2)
    
};


Runtime: 87 ms, faster than 28.23% of JavaScript online submissions for Convert Binary Number in a Linked List to Integer.



효율성 좋은 코드

/**
 * 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}
 */

const getDecimalValue = (head) => {
	let current = head; 
	let nums  = []; 
	while (current !== null) {
		nums.push(current.val);
		current = current.next; 
	}

	return parseInt(nums.join(''), 2)
}	

while문을 나의 코드보다 더 깔끔한 형식으로 했다.