标签:ret 状态 output ati nat input beat stop 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.
Java Solution:
Runtime beats 61.45%
完成日期:06/29/2017
关键词:Bit Manipulation
关键点:利用 & 1 判断最右边的bit; 利用 >> 来移动bits;判断num == 1 来终止反转
1 public class Solution 2 { 3 public int findComplement(int num) 4 { 5 int res = 0; 6 int x = 1; 7 8 for(int i=0; i<32; i++) 9 { 10 if((num & 1) == 0) // meaning num‘s bit is 0, need to flip this bit. 11 res += x; 12 13 x = x * 2; // increase the x 14 15 if(num == 1) // if current num is == 1, meaning all the leading numbers are zeros; stop 16 break; 17 18 num = num >> 1; // shift num to right by 1 bit. 19 20 } 21 22 return res; 23 } 24 }
参考资料:
http://www.cnblogs.com/grandyang/p/6275742.html
LeetCode 476. Number Complement (数的补数)
标签:ret 状态 output ati nat input beat stop not
原文地址:http://www.cnblogs.com/jimmycheng/p/7096888.html