有一个正整数,请找出其二进制表示中1的个数相同、且大小最接近的那两个数。(一个略大,一个略小) 给定正整数int x,请返回一个vector,表明所求的两个数(小的在前)。保证答案存在。 测试样例: 2程序员
返回:[1,4]面试
根据《程序员面试金典》上的位算数解法写的。 c01是拖尾0的个数,c01是拖尾0左方全为1的位的个数。p位除了拖尾0以外最最右边的0的位,p=c01+c11。x后一个数求取: 1.将位p置1; 2.将位0到p位清零; 3.将位0到c11-1位置1.测试
c1为拖尾1的个数,c0位拖尾1右方全为0的位的个数,p=c0+c1.则x前面一个数的求取步骤:code
#include <vector> classCloseNumber { public: vector<int> getCloseNumber(intx) { // write code here vector <int> result; int c01=0;//拖尾0的个数 int c11=0;//拖尾0左方全为1的个数 int c1=0;//拖尾1的个数 int c0=0;//拖尾1左方全为0的位个数 int c = x,d=x;//临时变量 //分别求取 while(((c & 1) == 0) && (c!=0)){ c01 ++; c >>= 1; } while((c & 1)==1){ c11 ++; c >>= 1; } while((d & 1)==1){ c1 ++; d >>= 1; } while(((d & 1) == 0) && (d!=0)){ c0 ++; d >>= 1; } result.push_back((x - (1<<(c1))-(1<<(c0-1)) +1)); result.push_back((x + (1<<(c11-1)) + (1<<c01) -1)); return result; } };