给定一个正整数,输出它的补数。补数是对该数的二进制表示取反。
示例 1:
输入: 5 输出: 2 解释: 5 的二进制表示为 101(没有前导零位),其补数为 010。所以你需要输出 2 。
示例 2:
输入: 1 输出: 0 解释: 1 的二进制表示为 1(没有前导零位),其补数为 0。所以你需要输出 0 。
注意:
- 给定的整数保证在 32 位带符号整数的范围内。
- 你可以假定二进制数不包含前导零位。
- 本题与 1009 https://leetcode-cn.com/problems/complement-of-base-10-integer/ 相同
import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; public class Solution476 { public int findComplement(int num) { String bins = Integer.toBinaryString(num); bins = bins.replace("1", "a"); bins = bins.replace("0", "1"); bins = bins.replace("a", "0"); int foo = Integer.parseInt(bins, 2); return foo; } public static void main(String[] args) { Solution476 sol = new Solution476(); int num = 5; System.out.println(sol.findComplement(num)); } }