标签:负数 需要 64位 code 填充 数值 移位运算符 val not
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
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.
Subscribe to see which companies asked this question
【题目分析】
给定一个正整数,对该数的二进制表示形式,从最高位的1开始向后按位取反。
【思路】
如果我们能知道该数最高位的1所在的位置,就可以构造一个长度和该数据所占位置一样长的一个掩码mask,然后概述和mask进行异或即可。
例如:5的二进制是101,我们的构造的掩码为mask=111,两者异或则为010,即是所要的结果。
【java代码1】
1 public class Solution { 2 public int findComplement(int num) { 3 int mask = 1, temp = num; 4 while(temp > 0) { 5 mask = mask << 1; 6 temp = temp >> 1; 7 } 8 return num^(mask-1); 9 } 10 }
【java代码2】
1 public class Solution { 2 public int findComplement(int num) { 3 int mask = (Integer.highestOneBit(num) << 1) - 1; 4 return num^mask; 5 } 6 }
Integer.highestOneBit(i)是一个什么样的函数呢?
1 publicstaticinthighestOneBit(int i) { 2 // HD, Figure 3-1 3 i |= (i >> 1); 4 i |= (i >> 2); 5 i |= (i >> 4); 6 i |= (i >> 8); 7 i |= (i >> 16); 8 return i - (i >>> 1); 9 }
1 public static long highestOneBit(long i) { 2 // HD, Figure 3-1 3 i |= (i >> 1); 4 i |= (i >> 2); 5 i |= (i >> 4); 6 i |= (i >> 8); 7 i |= (i >> 16); 8 i |= (i >> 32); 9 return i - (i >>> 1); 10 }
LeetCode 476. Number Complement
标签:负数 需要 64位 code 填充 数值 移位运算符 val not
原文地址:http://www.cnblogs.com/liujinhong/p/6279855.html