当前位置:网站首页>Leetcode- complement of numbers - simple

Leetcode- complement of numbers - simple

2022-06-13 05:49:00 AnWenRen

title :476 The complement of numbers - Simple

subject

Negates the binary representation of an integer (0 change 1 ,1 change 0) after , Then convert to decimal representation , You can get the complement of this integer .

for example , Integers 5 The binary representation of is “101” , Take the reverse and get “010” , Then turn back to decimal to get the complement 2 .
Give you an integer num , Output its complement .

Example 1

 Input :num = 5
 Output :2
 explain :5  The binary representation of  101( No leading zeros ), The complement is  010. So you need to output  2 .

Example 2

 Input :num = 1
 Output :0
 explain :1  The binary representation of  1( No leading zeros ), The complement is  0. So you need to output  0 .

Tips

  • 1 <= num < 231

Code Java

		public int findComplement(int num) {
    
        // 1.  Find the high position first 1
        int highbit = 0;
        for (int i = 31; i >= 0; i--) {
    
            if (((num >> i) & 1) != 0){
    
                highbit = i;
                break;
            }
        }
        // 2.  For high position all 1  To engage in exclusive or   have to   result 
        int result = highbit == 30 ? 0x7fffffff : (1 << (highbit + 1)) - 1 ;
        return  result ^ num;
    }
原网站

版权声明
本文为[AnWenRen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280507175657.html