1290. 二进制链表转整数

image.png

  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. type ListNode struct {
  7. Val int
  8. Next *ListNode
  9. }
  10. func getDecimalValue(head *ListNode) int {
  11. var list []int
  12. for head!=nil{
  13. list = append(list,head.Val)
  14. head = head.Next
  15. }
  16. var res int
  17. l := len(list)
  18. for i:=0;i<l;i++{
  19. if list[i]==1{
  20. r := int(math.Pow(2,float64(l-i-1)))
  21. res +=r
  22. }
  23. }
  24. return res
  25. }
  26. func main() {
  27. head :=&ListNode{Val:1}
  28. one :=&ListNode{Val:0}
  29. head.Next= one
  30. two :=&ListNode{Val:1}
  31. one.Next = two
  32. fmt.Println(getDecimalValue(head))
  33. }

image.png