LeetCode:1290. 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.

Golang的解法:
看Hint1是說,轉成string或是array,再一一轉成int。
我想了一下,感覺這樣寫蠻累的
看了Hint2說可以使用bit operation,馬上想出解法

這題要對位元和邏輯運算子熟悉

/** * Definition for singly-linked list. * type ListNode struct { *     Val int *     Next *ListNode * } */func getDecimalValue(head *ListNode) int {    number := 0    for {        if head.Val==1 {            number = number | 1        }        if head.Next == nil {            break        }        head = head.Next        number = number << 1    }    return number}

這題還算簡單

沒有留言:

張貼留言

About

努力在程式的大海
用力的揮動雙手
找出屬於自己的航線

Blog Archive

Traffic