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.
在这里插入图片描述
题目描述:将存放二进制数的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;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值