476. Number Complement
476. Number Complement
初雪之音 发表于10个月前
476. Number Complement
  • 发表于 10个月前
  • 阅读 106
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 技术升级10大核心产品年终让利>>>   

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

Note:

  1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
  2. 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.

 

Code:

public class Solution {
    public int findComplement(int num) {
		int result = 0;

		if (num > 0) {
			int temp = ~0;
			while ((temp & num) != 0) {
				temp <<= 1;
			}
			result = ~temp & ~num;
		}

		return result;
	}
}

 

标签: leetcode
共有 人打赏支持
粉丝 37
博文 229
码字总数 129645
×
初雪之音
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: