1009. Complement of Base 10 Integer
这是一道LeetCode上面的Easy题目,原文连接:https://leetcode.com/problems/complement-of-base-10-integer/
原文描述
Every non-negative integer N has a binary representation. For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on. Note that except for N = 0, there are no leading zeroes in any binary representation.
The complement of a binary representation is the number in binary you get when changing every 1 to a 0 and 0 to a 1. For example, the complement of "101" in binary is "010" in binary.
For a given number N in base-10, return the complement of it's binary representation as a base-10 integer.
Example 1:
Input: 5
Output: 2
Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
Example 2:
Input: 7
Output: 0
Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.
Example 3:
Input: 10
Output: 5
Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.
Note:
0 <= N < 10^9
该题是说把一个整数(0~10^9)的二进制取反得到的二进制,返回二进制对应的十进制
思路
先把该整数的二进制数的每一位取出来,进行取反,再把每一位二进制数转换为十进制数相加就能得到结果。由于在Java进行取反的时候会出现诡异的事件,具体还不知道什么原因。(有知道的大佬可以留言说明,感谢!)所以采用了另外类似的方法:先把该整数的二进制数的每一位取出来,跟1进行异或,再把每一位二进制数转换为十进制数相加就能得到结果。
取反:把二进制数由0变成1,由1变成0
异或:如果两个二进制数相同则为0,不相同则为1
取反说明
public static void main(String[] args) {
int n = 10;
System.out.println(n+"取反后的结果:"+~n);
int b = 0;
while(n>0){
b = ~(n&1);
System.out.println((n&1)+"取反的结果:"+b);
n = n>>1;
}
}
程序执行结果:
10取反后的结果:-11
0取反的结果:-1
1取反的结果:-2
0取反的结果:-1
1取反的结果:-2
算法实现
class Solution {
public int bitwiseComplement(int N) {
if(N == 0)return 1;
if(N == 1)return 0;
double num = 0;
int b = 0;
int i = 0;
while(N>0){
b = (N&1)^1;
num = num + b*Math.pow(2,i);
i++;
N = N>>1;
}
return (int)num;
}
}