【leetcode】 Single_Number_II

来源:互联网 发布:mac邮箱 imap无法连接 编辑:程序博客网 时间:2024/05/07 10:02

问题描述:

Given an array of integers, every element appears three times except for one. Find that single one.

解法:

设置一个32为的数组,第i位的数字对应元素出现的次数。我们把 第 ith个位置上所有数字的和对3取余,那么只会有两个结果 0 或 1.然后计算

 public int singleNumber(int[] A) { int[] count = new int[32]; for(int i=0;i<32;i++) count[i]=0; int result=0; for(int i=0;i<32;i++){ for(int j=0;j<A.length;j++){ System.out.println(j); if(((A[j]>>i)&1)!=0){ count[i]++; } } result|=((count[i]%3)<<i); }  return result;   }


0 0