首页 > 其他 > 详细

LeetCode:476. Number Complement

时间:2017-02-06 13:11:45      阅读:202      评论:0      收藏:0      [点我收藏+]
 1 package Today;
 2 //LeetCode:476. Number Complement
 3 /*
 4  Given a positive integer, output its complement number. 
 5  The complement strategy is to flip the bits of its binary representation.
 6 
 7 Note:
 8 The given integer is guaranteed to fit within the range of a 32-bit signed integer.
 9 You could assume no leading zero bit in the integer’s binary representation.
10 Example 1:
11 Input: 5
12 Output: 2
13 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
14 Example 2:
15 Input: 1
16 Output: 0
17 Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
18  */
19 public class findComplement476 {
20     public static int findComplement(int num) {
21         int bits=0;
22         int number=num;
23         while(number>0){
24             bits++;
25             number=number>>1;
26         }
27         return num^(int)(Math.pow(2,bits)-1);
28     }
29     //study 原来有方法可以直接得到最高bit位
30     public static int findComplement2(int num){
31         return num^((Integer.highestOneBit(num)<<1)-1);
32     }
33     public static void main(String[] args) {
34         //TODO Auto-generated method stub
35         System.out.println(findComplement(5));
36         System.out.println(findComplement(1));
37         System.out.println(findComplement2(5));
38         System.out.println(findComplement2(1));
39         
40     }
41 
42 }

 

LeetCode:476. Number Complement

原文:http://www.cnblogs.com/luluqiao/p/6369679.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!