判斷整型數中每一位的值(C++)
怎么獲取整形中某一位的值是最常見的面試題。 1
/**//*
2
Subject: the value of the each bit on int
3
Author: shexinwei
4
School: xidian university
5
Date: 2010-09-13
6
Laguage: C++
7
IDE: visual studio 6.o
8
Version: 1.0
9
Modify Time: 2010-09-13
10
*/
11
#include <iostream>
12
using namespace std;
13
int main()
14
{
15
int i = 0;
16
cout<<"please input the number:";
17
cin>>i;
18
char *result = new char[sizeof(int)*8];
19
int j = 1;
20
for (int k = 0;k<sizeof(int)*8;(j=j<<1),k++)
21
{
22
if ( (i&j) == 0 )
23
{
24
result[k] = '0';
25
}
26
else result[k] = '1';
27
}
28
for (int m = sizeof(int)*8-1;m >=0 ; m--)
29
{
30
cout<<result[m];
31
}
32
cout<<endl;
33
delete []result;
34
return 1;
35
}

/**//*2
Subject: the value of the each bit on int3
Author: shexinwei4
School: xidian university5
Date: 2010-09-136
Laguage: C++7
IDE: visual studio 6.o8
Version: 1.09
Modify Time: 2010-09-1310
*/11
#include <iostream>12
using namespace std;13
int main()14
{15
int i = 0;16
cout<<"please input the number:";17
cin>>i;18
char *result = new char[sizeof(int)*8];19
int j = 1;20
for (int k = 0;k<sizeof(int)*8;(j=j<<1),k++)21
{22
if ( (i&j) == 0 )23
{24
result[k] = '0';25
}26
else result[k] = '1';27
}28
for (int m = sizeof(int)*8-1;m >=0 ; m--)29
{30
cout<<result[m];31
}32
cout<<endl;33
delete []result;34
return 1;35
}

