题1290、二进制链表转整数

一、题目1

在这里插入图片描述
在这里插入图片描述

二、思路

三、代码

public class T1290 {

    public static void main(String[] args) {

//        int input[] = {1,0,1};              //5
//        int input[] = {0, 0};               //0
        int input[] = {1,0,0,1,0,0,1,1,1,0,0,0,0,0,0};               //18880
//        int input[] = {1};               //1

        ListNode root = new ListNode(input[0]);
        ListNode node = root;
        for ( int i = 1; i < input.length; i++ ){
            ListNode tmp = new ListNode(input[i]);
            node.next = tmp;
            node = node.next;
        }

        System.out.println( getDecimalValue(root));
    }

    public static int getDecimalValue(ListNode head) {

        //方案1
/*        String result = "";
        ListNode next = head;
        while ( next != null ){
            result += next.val;
            next = next.next;
        }

//        System.out.println( result );
//        System.out.println( Integer.valueOf(result,2));
        return Integer.valueOf(result,2);*/

        //方案2
        int result = 0;
        ListNode node = head;

        while ( node != null ){
            result *= 2;
            result += node.val;
            node = node.next;
        }

        return result;
    }

}

//Definition for singly-linked list.
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}


  1. 来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/convert-binary-number-in-a-linked-list-to-integer
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ↩︎

发布了48 篇原创文章 · 获赞 1 · 访问量 861

猜你喜欢

转载自blog.csdn.net/weixin_45980031/article/details/104117698