Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

1290. 二进制链表转整数 #23

Open
GpingFeng opened this issue Dec 25, 2020 · 1 comment
Open

1290. 二进制链表转整数 #23

GpingFeng opened this issue Dec 25, 2020 · 1 comment

Comments

@GpingFeng
Copy link
Owner

1290. 二进制链表转整数

解题思路

  • 反转链表
  • 遍历链表,对应的位置下边值为 2^i
  • 返回和
var getDecimalValue = function(head) {
  // 反转一次链表
  let prev = null;
  let cur = head;
  while(cur) {
    [prev, cur.next, cur] = [cur, prev, cur.next]
  }
  let i = 0;
  let sum = 0;
  while(prev) {
    if (prev.val) {
      // 有值的时候进行二进制指数运算
      sum += Math.pow(2, i);
    }
    prev = prev.next;
    i++;
  }
  return sum;
};

复杂度分析

  • 时间复杂度——O(n)
  • 空间复杂度——O(1)
@GpingFeng
Copy link
Owner Author

解法二

其实从开始遍历到结束也是可以做到的

var getDecimalValue = function(head) {
  let sum = 0;
  while(head) {
    sum = sum * 2 + head.val;
    head = head.next;
  }
  return sum;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant