[求下面函数的返回值]代码验证

看到一道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。

此问题不知为何,欢迎大家讨论


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值