xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js 进制转换

js 进制转换

js & notes

parseInt & toString

let result = [1,0,1];

result = [1,0,1].join()
// "1,0,1"
result = [1,0,1].join(``)
// "101"
result = parseInt([1,0,1].join(``))
// 101

result.toString(10);
// "101"
result.toString(2);
// "1100101"

parseInt([1,0,1].join(``));
// 101
parseInt([1,0,1].join(``), 2);
// 5

const log = console.log;

// 十进制转其他进制
const x = 110;

log(x.toString(2));
log(x.toString(8));
log(x.toString(16));

// 其他进制转十进制
const x = `110`;

log(parseInt(x, 2));
log(parseInt(x, 8));
log(parseInt(x, 16));

// 其他制转转其他制转
// 先用 parseInt 转成十进制, 再用 toString 转到目标进制

log(String.fromCharCode(parseInt(141, 8)))
log(parseInt('ff', 16).toString(2)); 

LeetCode

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

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {number}
 */
var getDecimalValue = function(head) {
    const result = [];
    while(head) {
      result.push(head.val)
      head = head.next;
    }
    return parseInt(result.join(``), 2);
};

位运算

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {number}
 */
var getDecimalValue = function(head) {
  let val = 0;
  while (head) {
    val = (val << 1) | head.val;
    head = head.next;
  }
  return val;
};

refs

https://www.jianshu.com/p/6f60a6b7f3b8

https://blog.csdn.net/lk188/article/details/4317459

https://juejin.im/post/6844903846209126407



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


posted @ 2020-08-20 09:36  xgqfrms  阅读(205)  评论(3编辑  收藏  举报