zoukankan      html  css  js  c++  java
  • LeetCode-1290.Convert Binary Number in a Linked List to Integer

    Convert Binary Number in a Linked List to Integer

    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.

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

    请你返回该链表所表示数字的 十进制值 。

    Example 1:

    Input: head = [1,0,1]
    Output: 5
    Explanation: (101) in base 2 = (5) in base 10

    Example 2:

    Input: head = [0]
    Output: 0

    Example 3:

    Input: head = [1]
    Output: 1

    Example 4:

    Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0]
    Output: 18880

    Example 5:

    Input: head = [0,0]
    Output: 0

    Constraints:

    The Linked List is not empty.
    Number of nodes will not exceed 30.
    Each node's value is either 0 or 1.

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public int getDecimalValue(ListNode head) {
    		if (head == null)
    			return 0;
    		int ans = 0;
    		while (head != null) {
    			ans = (ans << 1) + head.val;
    			head = head.next;
    		}
    		return ans;
        }
    }
    
  • 相关阅读:
    设计模式大赛 -- 大话设计模式
    访问者模式 -- 大话设计模式
    puts的用处
    scanf的使用
    iOS,手势识别简单使用
    iOS,多媒体,地图相关
    iOS,文本输入,键盘相关
    iOS,XMPP本地环境搭建和框架使用
    iOS,自动布局autoresizing和auto layout,VFL语言
    iOS,图片处理
  • 原文地址:https://www.cnblogs.com/pengcode/p/15324088.html
Copyright © 2011-2022 走看看