Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
2.后来自定义一个itoa1()实现整数转换为二进制字符串,利用stack<int>容器承接,还是不行:‘stack’ undeclared (first use in this function)
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.
汉明权重指的是在一条字符串里 不同于’0‘字符的的这样的字符数目。
Hammingcode是指一个字串中非0符号的个数(TheHamming weight of a stringis the number of symbols that are different from the zero-symbol ofthealphabetused.)。应用到2进制符号序列中来,即二进制串中1的个数就是该串的Hammingcode.那么上述的问题即转换成求解字串的Hammingcode的问题。例如:
1.本来想利用自带的itoa()函数实现整数向二进制转换,没想到提交之后 implicit declaration of function ‘itoa’:
int hammingWeight(uint32_t n) {
char c[33];
memset(c,0,sizeof(c));
itoa(n,c,2);
int k=0;
int l=strlen(c);
for(int i=0;i<l;i++)
if(c[i]=='1')k++;
return k;
}
2.后来自定义一个itoa1()实现整数转换为二进制字符串,利用stack<int>容器承接,还是不行:‘stack’ undeclared (first use in this function)
void itoa1(uint32_t n,char *s){
stack<int>ss;
int i=0;
do{ss.push(n%2);n=n/2;}while(n!=0);
while(!ss.empty())
{
s[i++]=ss.top()+'0';
ss.pop();
}
s[i]='\0';
}
int hammingWeight(uint32_t n) {
char c[33];
memset(c,0,sizeof(c));
itoa1(n,c);
int k=0;
int l=strlen(c);
for(int i=0;i<l;i++)
if(c[i]=='1')k++;
return k;
}
3.最终:
void itoa1(uint32_t n,char *s){
int i=0;
do{s[i++]=(n%2)+'0';n=n/2;}while(n!=0);
s[i]='\0';
}
int hammingWeight(uint32_t n) {
char c[33];
memset(c,0,sizeof(c));
itoa1(n,c);
int k=0;
int l=strlen(c);
for(int i=0;i<l;i++)
if(c[i]=='1')k++;
return k;
}
4.输出反序后的整数:
void itoa1(uint32_t n,char *s){
int i=0;
do{s[i++]=(n%2)+'0';n=n/2;}while(n!=0);
s[i]='\0';
}
uint32_t reverseBits(uint32_t n) {
char c[33]={'0'};
itoa1(n,c);
int l=strlen(c);
if(l<33)
{for(int i=l;i<32;i++)
c[i]='0';
c[32]='\0';}
uint32_t sum=0;
for(int i=0;i<32;i++)
{
sum*=2;
sum+=c[i]-'0';}
return sum;
}