首页 > 代码库 > LeetCode:476. Number Complement
LeetCode:476. Number Complement
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。