[LeetCode] 476. Number Complement

Given a positive integer num, output its complement number. The complement strategy is to flip the bits of its 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.

数字的补数。题意是给一个正整数,请你返回他的二进制的补数。为什么要标红正整数,是因为这道题跟1009题还是有点区别的。1009的条件是非负整数,如果还是用这道题的办法,遇到0会报错,因为0的补数是1。

既然是找二进制的补数,自然是位运算了。因为求的是补数,所以原来是1的digit要变成0,原来0的地方要变成1,所以思路就是找一个数字,每次不断向左移动一位,并和1做与的操作(“|”)。因为sum一开始是0,所以每一位与1的结果都是1。但是这个题巧妙的地方在于,补数 = 若干个1 - 原来的数。例子,比如原来的数字是6好了,二进制是110。他的补数1(001)= 111 - 110。这不是一个巧合,所有的数字都满足这个条件。

时间O(1)

空间O(1)

Java实现

1 class Solution {
2     public int findComplement(int num) {
3         int sum = 0;
4         while (sum < num) {
5             sum = (sum << 1) | 1;
6         }
7         return sum - num;
8     }
9 }

 

LeetCode 题目总结

posted @ 2020-05-05 12:32  CNoodle  阅读(191)  评论(0编辑  收藏  举报