【leetcode】1009. Complement of Base 10 Integer
The complement of an integer is the integer you get when you flip all the 0
's to 1
's and all the 1
's to 0
's in its binary representation.
- For example, The integer
5
is"101"
in binary and its complement is"010"
which is the integer2
.
Given an integer n
, return its complement.
Example 1:
Input: n = 5
Output: 2
Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
Example 2:
Input: n = 7
Output: 0
Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.
Example 3:
Input: n = 10
Output: 5
Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.
Constraints:
0 <= n < 109
这道题和476. Number Complement 做法几乎完全相同,唯一的区别就是476的num从1开始,这题需要单独考虑0的问题,做这题的时候要注意 mask 必须为unsigned,leetcode 编译器禁止了-1的左移。 不同编译器应该不同。
class Solution {
public:
int bitwiseComplement(int n) {
// use bit mark to slove
if(n==0) return 1;
unsigned mask=~0;
while(mask&n) mask=mask<<1;
return ~n^mask;
}
};
计算机中负数是以补码存储的,也可以推广到,计算机中所有数都是以补码形式存储的。(正数的原码、反码、补码三码合一),补码的存在是为了方便正数和负数进行计算。
原码 | 反码 | 补码 | |
10 | 0000 1010 | 0000 1010 | 0000 1010 |
-1 | 1000 0001 | 1111 1110 | 1111 1111 |
+ | 1000 1011(-11) | 1 0000 1001溢出=0000 1001(9) |
所以计算机实际上存储的是数字的反码。
1.单字节无符号的正数可以存储的范围就是 0~256 二进制表示( 0000 0000~1111 1111)
2.单字节有负号的整数可以存储的范围是-128 ~127 。
先看正数二进制能表示范围(0 000 0001 ~ 0 111 1111)即1~127
负数二进制能能表示的范围(1 000 0001 ~ 1 111 1111)即-127(反码为1000 0001)~-1(反码为1111 1111)
所还有个0 分为+0和-0 (0000 0000 表示+0,1000 0000 表示-0 表示-128)