首页 > 代码库 > leetcode 476. Number Complement

leetcode 476. Number Complement

给定一个正整数,输出其补码。

思路:利用mask掩码进行异或,

     

 1 public class Solution {
 2     public int findComplement(int num) {
 3         int mask = 1 , temp = num;
 4         while(temp>0){
 5             mask = mask << 1;
 6             temp = temp >> 1;
 7         }
 8         return num^(mask - 1);
 9     }
10 }

 

leetcode 476. Number Complement