注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
根据其他人的讲解,这是代码
- class Solution {
- public int singleNumber(int[] nums) {
- int result = 0;
- //loop through all bits
- for (int i = 0; i < 32; i ++ ) {
- // loop through all numbers
- int sum = 0;
- for (int num : nums) {
- // get the corresponding bit
- int temp = num >> i & 1;
- // sum it up
- sum = sum + temp;
- }
- // put bit to the corresponding position of result
- result = (sum % 3 << i) | result;
- }
- return result;
- }
- }
复制代码
我不是特别理解 (sum%3<<i)|result
sum % 3 结果可以是 0, 1, 2. 如果结果是0和1的话,那么通过(sum%3<<i)|result,这个bit会被放在result的恰当位置上,不会影响下一个bit. 但是如果是2的话,2进制表示下是10, (sum%3<<i)|result不就会影响之后的bit吗?
比如,首先假设第2个bit上 sum % 3 = 2, 那么二进制 10 << 2 | 0011 = 1011, 然后假设第3个bit上 sum % 3 = 1, 那么二进制01 << 3 | 1011 = 1011, 相当于第三个bit上01这个结果没有被考虑进去。
|