LeetCode 1290-二进制链表转整数

1. 二进制链表转整数(10进制)

public class GetDecimalValue1290 {
    //定义一个单链表
    public class ListNode {
        int val;           //当前节点值
        ListNode next;     //下一个节点值
        //构造方法 初始化当前节点值
        ListNode(int x) { val = x; }
    }
    
    //方法1:数学思想(累加) 时间复杂度 O(n)
    public int getDecimalValue01(ListNode head) {
        int sum = 0;
        while(head!=null){
            sum = sum*2 + head.val;
            head = head.next;
        }
        return sum;
    }

    //方法2:位运算  时间复杂度 O(n)
    public int getDecimalValue(ListNode head) {
        ListNode cur = head;
        int sum = 0;
        while (cur != null) {
            sum <<= 1;
            sum += cur.val;
            cur = cur.next;
        }
        return sum;
    }
}

2. LeetCode代码测试

发布了60 篇原创文章 · 获赞 0 · 访问量 2886

猜你喜欢

转载自blog.csdn.net/weixin_45450428/article/details/103970943