看到一道C++面试题
求下面函数的返回值(微软)
int func(x)
{
int countx = 0;
while(x)
{
countx ++;
x = x&(x-1);
}
return countx;
}
假定x = 9999。 答案:8
思路:将x转化为2进制,看含有的1的个数。
-----------------------------------
下面为博主的测试结果:
程序内容如下,
#include<stdio.h>
#include <stdlib.h>
// #include <iostream>
// using namespace std;
int func(int x)
{
int countx=0;
char p[50],p1[50];
itoa(x,p,2);
itoa(x-1,p1,2);
printf("x : %016s\nx-1: %016s\nx : %d\n----------------------\n",p,p1,x);
while(x)
{
countx++;
x = x&(x-1);
itoa(x,p,2);
itoa(x-1,p1,2);
printf("x : %016s\nx-1: %016s\nx : %d\n----------------------\n",p,p1,x);
}
return countx;
}
void main()
{
int output = func(9999);
printf("output = %d\n",output);
// char ss[100];
// itoa(-1,ss,2);
// printf("ss = %s\n",ss);
// cout<<"ss = "<<ss<<endl;
}
输出结果为:
----------------------------------------
以下为题外话:
itoa函数对负数【-1】转换成二进制数,呈现为奇怪结果【32个数字1】,换算成十进制为:8589934591。
此问题不知为何,欢迎大家讨论