Single Number

除了一个出现1次,其他的数字都出现了3次,找出出现1次的数字

32位的二进制中,每一位要么是0,要么是1;

对于数组中的元素,每一个元素其某一位出现1的次数的和,肯定是3N或3N+1次,则次数和对3取模必定是只出现1次的元素在该位的值,即是0或1。

代码:

public class Solution {
    /**
   *出现的次数NUMBER,其他的数字出现次数为1,找出出现次数为1的数
   */
public int NUMBER = 3; public int singleNumber(int[] A) { int result = 0; for (int i = 0; i < 32; i++) { int temp = 0; for (int j = 0, len = A.length; j < len; j++) { temp += 1 & (A[j] >> i); } result = result | ((temp % NUMBER) << i); } return result; } }

方法二:

 public int NUM = 3;
    public int singleNumber(int[] nums) {
        int ret = 0, mask = 0, c = 0;
        for(int i = 0;i < 32;i ++){
            mask = 1<<i;
            c = 0;
            for(int j = 0, len = nums.length;j < len;j ++){
                if((nums[j]&mask) != 0){
                    c ++;  
                }
            }
            if(c % NUM != 0){
                ret = ret | mask;
            }
        }
        return ret;
    }
原文地址:https://www.cnblogs.com/xiaoxian1369/p/3632028.html