Single Number II

来源:互联网 发布:大数据产业园规划 编辑:程序博客网 时间:2024/05/01 03:16

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

public int singleNumber(int[] A) {if (A == null || A.length == 0)return 0;int[] a = new int[32];for (int i = 0; i < A.length; i++) {for (int j = 0; j < 32; j++) {//1<<j == 1向左移动j位//A[i] & (1 << j)可以判断A[i]二进制中有哪几位为1if ((A[i] & (1 << j)) != 0)//[j]这是倒过来的//e.g A[i] = 11 = 1011 ==>//a[j] = 11010000...//+1 %3后,所有出现3次的数变为0a[j] = (a[j] + 1) % 3;}}int result = 0;for (int i = 0; i < 32; i++) {if (a[i] > 0)//a[i] << i将反过来的结果正过来result |= (a[i] << i); }return result;}

http://shmilyaw-hotmail-com.iteye.com/blog/2153924

0 0
原创粉丝点击