LeetCode:476. Number Complement
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode-476-Number Complement]
LeetCode(476): Number Complement
leetcode-476-Number Complement
LeetCode 476. Number Complement (数的补数)