Home > AI > Data Structure > Graph >

leetcode-1290-Convert Binary Number in a Linked List to Integer

Question link: https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/

Solution – Swift:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init() { self.val = 0; self.next = nil; }
 *     public init(_ val: Int) { self.val = val; self.next = nil; }
 *     public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
 * }
 */
import Foundation

class Solution {
    
    var tmp: [Int] = []
    
    func getDecimalValue(_ head: ListNode?) -> Int {
        var ok: ListNode? = head
        while ok != nil {
            tmp.append(ok!.val)
            ok = ok!.next
        }
        
        var c = tmp.count
        var s = 0
        for t in tmp {
            s += t * Int(pow(Double(2), Double(c-1)))
            c -= 1
        }
        return Int(s)
    }
}
Relevant tags:

Leave a Reply