第四天,但是……这一题写错了,方法不对,超出时间限制,优化答案明天再想想,先把我刚刚想到的宛如智障般的答案拿出来遛遛……
第五天更新,修改成了正儿八经的求二进制反码的十进制数……写出来其实也不是很复杂。
贴原题:
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
The given integer is guaranteed to fit within the range of a 32-bit
signed integer. You could assume no leading zero bit in the integer’s
binary representation. Example 1:Input: 5 Output: 2 Explanation: The binary representation of 5 is 101
(no leading zero bits), and its complement is 010. So you need to
output 2. Example 2:Input: 1 Output: 0 Explanation: The binary representation of 1 is 1
(no leading zero bits), and its complement is 0. So you need to output
0.
贴C码:
int findComplement(int num) {
int n=1;
while(num>=n)
{
n*=2;
}
return n-num-1;
}
说一下我的傻逼之处吧
这道题是让求一个十进制正整数的二进制反码的十进制……呃……是的没说错!然后我就直接求了那个数的二进制所能表示的最大的数,也是模,然后用模减去那个十进制数。讲道理是没有问题的,我测试了好多数也没有问题,但是,最让我担心的事发生了,时间超出!果然偷懒还是不行啊……
本文明天继续更……
就酱
正儿八经的C代码:
int findComplement(int num) {
int m=1;
int output=0;
do
{
if(num%2==0)
{
output+=m;
}
m*=2;
}while(num/=2);
return output;
}
解析:
因为是二进制,所以为0的位不需要考虑,也不需要乘上非0位的1,只需要把原本十进制数的二进制为0的位的权重值相加即可。