137. 只出现一次的数字 II

https://leetcode.cn/problems/single-number-ii/description/?envType=study-plan-v2&envId=top-interview-150
 

只有一个数出现一次其与数都出现三次,我们可以统计所有数用二进制表示后的每位数上的情况,将所有数的二进制表示后各位数相加;显然只有目标数涉及到的位数上的情况无法被三整除,我们找出这些位数然后就可以组合成目标数了。

class Solution {
    public int singleNumber(int[] nums) {
        int[] arr = new int[32];
        for (int num : nums) {
            int cnt = 0;
            // 累加各数二进制情况
            while(cnt < 32) {
                if((num & 1) == 1) arr[cnt]++;
                num >>= 1;
                cnt++;
            }
        }
        int ans = 0;
        // 是负数我们记录的是补码形式还要再变回来
        if(arr[31] % 3 != 0) {
            for(int i = 0; i < 32; i++) {
                if(arr[i] % 3 == 0) {
                    ans += Math.pow(2, i);
                }
            }
            ans += 1;
            ans *= -1;
        } else {
            for (int i = 0; i < 31; i++) {
                if (arr[i] % 3 == 1) {
                    ans += Math.pow(2, i);
                }
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.singleNumber(new int[]{-2,-2,1,1,4,1,4,4,-4,-2}));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值