您的位置:首页 > 其它

[Leetcode]Single Number && Single Number II

2015-03-12 22:12 393 查看
Given an array of integers, every element appears twice except for one. Find that single one.

非常简单的一道题。

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

class Solution {
public:
int singleNumber(int A[], int n) {
int temp;
for(int i=0;i!=n;i++)
temp=temp^A[i];
return temp;
}
};


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

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

class Solution {
public:
int singleNumber(int A[], int n) {
int one=0,two=0,three=0;
for(int i=0;i!=n;i++){
three = A[i] & two;
two=two | (one & A[i]);
one = one | A[i];
one = one & ~three;
two = two & ~three;
}
return one;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: