一、题目地址
https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-ii-lcof/comments/
二、具体代码
/**
* @param {number[]} nums
* @return {number}
*/
// 位运算,通用模版
// 时间复杂度:O(N)
// 空间复杂度:O(1)
var singleNumber = function(nums) {
// 正确做法,需要加上每一位填充0的细节
let counts = new Array(32).fill(0);
/*
错误做法,理由见打印结果:
let counts = new Array(32);
console.log(counts[1]);//undefind
*/
for(let num of nums) {
for(let j=0; j<32; j++) {
counts[j] += (num & 1);
num >>>= 1;
}
}
let res = 0, m = 3;
for(let i=0; i<32; i++) {
res <<= 1;
res |= (counts[31-i] % m);
}
return res;
};
三、补充链接
https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-ii-lcof/solution/mian-shi-ti-56-ii-shu-zu-zhong-shu-zi-chu-xian-d-4/