본문 바로가기

Algorithms

1290. 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.

 

링크드리스트의 각 노드 값은 0 또는 1 이다,. 링크드리스트는  이진수를 표현한다.

결과는 이진수를 10진수로 반환한다.

 

Input: head = [1,0,1]

Output: 5

Explanation: (101) in base 2 = (5) in base 10

 

Input: head = [0]

Output: 0

 

Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0]

Output: 18880

 

 

비트 연산

a = 0011
b = 0110

a|b = 0111 // a OR b
a&b = 0010 // a AND b
a^b = 0101 // a XOR b
(~a&b)|(a&~b) = 0101
~a = 1100 // NOT a

 

 

public class Solution {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public static int getDecimalValue(ListNode head) {
        int ans = 0;
        while (head != null) {
            ans = (ans << 1) | head.val;
            head = head.next;
        }
        return ans;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode node1 = new ListNode(0);
        ListNode node2 = new ListNode(1);

        head.next = node1;
        node1.next = node2;

        getDecimalValue(head);

    }
}

 

https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/

 

Convert Binary Number in a Linked List to Integer - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

'Algorithms' 카테고리의 다른 글

싱글 링크드리스트 삭제하기  (0) 2022.08.09
싱글 링크드리스트 추가하기  (0) 2022.08.09
동적 계획법  (0) 2020.07.20
Palindrome(회문) 알고리즘  (0) 2020.07.14
leetcode 1281번 문제풀이  (0) 2020.03.26