HTMLify

LeetCode - Convert Binary Number in a Linked List to Integer - Go
Views: 3 | Author: abh
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func getDecimalValue(head *ListNode) int {
    bin := ""
	for ;head!=nil; {
		if head.Val == 1 {
			bin = "1" + bin
		} else {
			bin = "0" + bin
		}
		head = head.Next
	}
	p := 1
	var d int
	for _, b := range bin {
		if b == '1' {
			d += p
		}
		p *= 2
	}
	return d
}

Comments