微软面试题【2】

来源:互联网 发布:淘宝有哪些好吃的零食 编辑:程序博客网 时间:2024/05/22 05:30

            求下面函数的返回值(微软)

            

int func(int x){int count = 0;while(x){count++;x = x & (x-1);}return (count);}


            自己补充的完整代码:

             

#include<iostream>using namespace std;int func(int x){int count = 0;while(x){count++;x = x & (x-1);}return (count);}int main(){int x = 0;cout<<"Input: ";cin>>x;x = func(x);cout<<"Return: "<<x<<endl; return 0;}


             运行结果:(思路:将x转化为2进制,看含有的1的个数)

              

               


              注: 每执行一次x = x&(x-1),会将x用二进制表示时最右边的一个1变为0,因为x-1将会将该位(x用二进制表示时最右边的一个1)变为0。

即:x = 1111, x-1 = 1110, 则 x&(x-1) = 1100.

原创粉丝点击