找出数组中两个只出现一次的数字
来源:互联网 发布:app借款软件排行 编辑:程序博客网 时间:2024/06/06 18:35
题目:一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字
通过这道题感觉位运算很强大~这道题利用异或的几个性质:任何数与其本身异或值都为0,异或运算满足交换律。因此将一组数依次异或,若里面只有一个只出现一次的数,其他的数都出现两次,则最后的结果必然是那个只出现一次的数。要找到两个数字就可以先通过异或整个数组,将得到的结果分组。然后依次安组异或就可以得到所求的值~
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include<iostream>
using
namespace
std;
int
findFirstOne(
int
value);
bool
testBit(
int
value,
int
pos);
int
findNums(
int
date[],
int
length,
int
&num1,
int
&num2){
if
(length<2){
return
-1;}
int
ansXor=0;
for
(
int
i=0;i<length;i++){
ansXor^=date[i];
//异或
}
int
pos=findFirstOne(ansXor);
num1=num2=0;
for
(
int
i=0;i<length;i++){
if
(testBit(date[i],pos))
num1^=date[i];
else
num2^=date[i];
}
return
0;
}
int
findFirstOne(
int
value){
//取二进制中首个为1的位置
int
pos=1;
while
((value&1)!=1){
value=value>>1;
pos++;
}
return
pos;
}
bool
testBit(
int
value,
int
pos){
//测试某位置是否为1
return
((value>>pos)&1);
}
int
main(
void
){
int
date[10]={1,2,3,4,5,6,4,3,2,1};
int
ans1,ans2;
if
(findNums(date,10,ans1,ans2)==0)
cout<<ans1<<
" "
<<ans2<<endl;
else
cout<<
"error"
<<endl;
return
0;
}
0 0
- 找出数组中两个只出现一次的数字
- 找出数组中两个只出现一次的数字--总结
- 找出数组中两个只出现一次的数字
- 找出数组中两个只出现一次的数字
- 找出数组中两个只出现一次的数字
- 找出数组中两个只出现一次的数字
- 找出数组中两个只出现一次的数字
- 找出数组中两个只出现一次的数字
- 找出数组中两个只出现一次的数字
- 找出数组中两个只出现一次的数字
- 找出数组中两个只出现一次的数字
- 找出数组中两个只出现一次的数字
- 找出数组中两个只出现一次的数字
- 找出数组中两个只出现一次的数字
- 找出数组中两个只出现一次的数字
- 找出数组中两个只出现一次的数字
- 找出数组中两个只出现一次的数字
- 找出数组中两个只出现一次的数字
- 常用算法之冒泡排序
- 持续集成
- Error: Module did not self-register.
- ssd性能
- 设计模式之观察者模式
- 找出数组中两个只出现一次的数字
- 使用C++类对象,运行后无法读取内存
- VPN简介
- FaceBook推出的开源图片加载库,fresco
- EF实体类指定部分属性不映射成数据库字段的方法
- Android Wi-Fi基本操作
- 0.11之路(一):BIOS引导过程
- 怎样使用Cocos LUACompile
- NDK编译错误总结