Leetcode 137: Single Number II

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

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

 

 1 public class Solution {
 2     public int SingleNumber(int[] nums) {
 3         int result = 0, bitMask = 0x1;
 4         
 5         for (int i = 0; i < 32; i++)
 6         {
 7             int count = 0;
 8             for (int j = 0; j < nums.Length; j++)
 9             {
10                 int d = nums[j] & bitMask;
11                 if (d != 0) count++;
12             }
13             
14             if (count % 3 != 0)
15             {
16                 result |= bitMask;
17             }
18             
19             bitMask <<= 1;
20         }
21         
22         return result;
23     }
24 }

 

posted @ 2017-11-22 05:51  逸朵  阅读(113)  评论(0)    收藏  举报