Skip to content

Instantly share code, notes, and snippets.

@Gowtham-369
Created May 4, 2020 12:11
Show Gist options
  • Save Gowtham-369/837c2dcf06373dae435873c7dafbfd28 to your computer and use it in GitHub Desktop.
Save Gowtham-369/837c2dcf06373dae435873c7dafbfd28 to your computer and use it in GitHub Desktop.
Day4 : 30 Day LeetCode may challenges
//overcome runtime error by not doing n=n*2 operation causing overflow
class Solution {
public:
int findComplement(int num) {
/*
5/2 = 2 and 5%2 = 1
2/2 = 1 and 2%2 = 0
1/2 = 0 and 1%2 = 1
*/
/*int sum = 0;
int l = 1;
while(num != 0){
if(num%2==0){
sum+=l;
}
l = l*2;
num = num/2;
}
return sum;
*/
/*
long long n = 1;
while((int)n<=num){
n = n*2;
}
return (int)(n-num-1);
*/
int i;
//if (num == 0)
//return 1;
for(i = 1; i<=31; i++){
if(num == pow(2,i))
return num-1;
else if(num < pow(2,i))
break;
}
return (pow(2,i)-1-num);
}
};
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Example 1:
Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Example 2:
Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
Note:
i . The given integer is guaranteed to fit within the range of a 32-bit signed integer.
ii. You could assume no leading zero bit in the integer’s binary representation.
iii.This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment