leetcode - Convert Binary Number in a Linked List to Integer - Java

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.
leetcode - Convert Binary Number in a Linked List to Integer - Java_第1张图片
题目描述:将存放二进制数的LinkedList转换为int类型
思路:此题第一眼看觉得直接递归好一点,可递归的话没办法 知道当前的深度,卡住了。用栈或者队列会更好实现。但在这有一种更好实现的方法:将数从list中取出,将结果左移

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

你可能感兴趣的:(LeetCode)