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

非常简单的一道题。

直接相异或剩下的那个数就是答案。原理是两个相等的数异或的值为0。

1 class Solution {
2 public:
3     int singleNumber(int A[], int n) {
4         int temp;
5         for(int i=0;i!=n;i++)
6             temp=temp^A[i];
7         return temp;
8     }
9 };

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

用好位运算,多看看与或非到底能做什么。

 1 class Solution {
 2 public:
 3     int singleNumber(int A[], int n) {
 4         int one=0,two=0,three=0;
 5         for(int i=0;i!=n;i++){
 6             three = A[i] & two;
 7             two=two | (one & A[i]);
 8             one = one | A[i];
 9             one = one & ~three;
10             two = two & ~three;
11         }
12         return one;
13     }
14 };

 

相关文章:

  • 2021-11-01
  • 2021-08-19
  • 2022-12-23
  • 2021-12-09
  • 2022-01-06
  • 2021-08-13
  • 2021-06-30
  • 2022-02-22
猜你喜欢
  • 2021-09-28
  • 2021-09-20
  • 2022-01-01
  • 2021-06-12
  • 2021-12-16
  • 2021-07-19
  • 2022-12-23
相关资源
相似解决方案