码迷,mamicode.com
首页 > 其他好文 > 详细

1290. Convert Binary Number in a Linked List to Integer

时间:2020-04-29 00:53:52      阅读:52      评论:0      收藏:0      [点我收藏+]

标签:for   div   pre   pac   ++   tps   package   ima   leetcode   

package LeetCode_1290

/**
 * 1290. Convert Binary Number in a Linked List to Integer
 * https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/description/
 * */

class ListNode(var `val`: Int) {
    var next: ListNode? = null
}

class Solution {
    fun getDecimalValue(head_: ListNode?): Int {
        var result = 0
        var len = 0.0
        var node = head_
        var head = head_
        while (node != null) {
            len++
            node = node.next
        }
        len--
        //binary to decimal by math formula: (base two) 101 = 1*2^2 + 0*2^1 + 1*2^0
        while (head != null) {
            result += head.`val` * Math.pow(2.0, len--).toInt()
            head = head.next
        }
        return result
    }
}

 

1290. Convert Binary Number in a Linked List to Integer

标签:for   div   pre   pac   ++   tps   package   ima   leetcode   

原文地址:https://www.cnblogs.com/johnnyzhao/p/12799322.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!