无尽算法之 二进制链表转整数

给你一个单链表的引用结点 head。链表中每个结点的值不是 0 就是 1。已知此链表是一个整数数字的二进制表示形式。

请你返回该链表所表示数字的 十进制值 。
示例一:
在这里插入图片描述

输入:head = [1,0,1]
输出:5
解释:二进制数 (101) 转化为十进制数 (5)

算法实现

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int getDecimalValue(ListNode head) {
        ListNode newHead=reverseList2(head);
        int factor=0;
        int total=0;
        ListNode temp=newHead;
        while(temp!=null){
            total+=temp.val*Math.pow(2,factor);
            factor+=1;
            temp=temp.next;
        }
        return total;
    }
    ListNode reverseList2(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseList2(head.next);
        head.next.next=head;
        head.next=null;
        return newHead;
    }
}
发布了125 篇原创文章 · 获赞 236 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_33709508/article/details/103791855