Problem:
Given an array of integers, every element appears three times except for one. Find the single one.
Note:
Your algorithm should has a linear runtime complexity. Could you implement it without using extra memory?
Hide TagsBit ManipulationTest instructions: In an array, only one element appears once, the other elements appear k times, (K is odd 3)
Thinking:
(1) This problem applies to the occurrence of odd times, the solution is: each of the number of all numbers of the occurrence of 1 of the number of statistics, the K after the remainder, for the number of bits to be asked in the number of digits (0 or 1),
Convert 2 binary to 10 binary
(2) This problem I assume int is 32 bits, some machines are not 32 bits.
Code
Class Solution {public: int singlenumber (vector<int>& nums) { string s; int a=0x0001; int count=0; for (int i=0;i<32;i++) {for (int j=0;j<nums.size (); j + +) { if ((nums[j]&a)!=0) count+ +; } S.push_back (' 0 ' +count%3); a=a<<1; count=0; } return Reverse_string_to_int (s); } Protected: int Reverse_string_to_int (string s) { int a=1; int ret=0; for (int i=0;i<s.size (); i++) { ret+= (s.at (i)-' 0 ') *a; a*=2; } return ret; }};
Leetcode | | 137, single number II