Number Complement LeetCode Solution - The Coding Shala
Home >> LeetCode >> Number Complement
Other Posts You May Like
In this post, we will learn how to solve LeetCode's Number Complement Problem and will implement its solution in Java.
Number Complement Problem
Given a positive integer num, output its complement number. The complement strategy is to flip the bits of its binary representation.
Example 1:
Input: num = 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.
Practice this problem on LeetCode.
LeetCode - Number Complement Java Solution
Approach 1
Just flip the bit and make decimal value from it.
Java Program:
class Solution { public int findComplement(int num) { int ans = 0; int two = 1; while(num > 0) { //if bit is 0 then flip and make binary of result if(num%2 == 0) { ans += two; } two *= 2; num /= 2; } return ans; } }
Approach 2
Using bit Manipulation.
Java Program:
class Solution { public int findComplement(int num) { int ans = 0; int i = 31; //find first 1 from left while(num >> i == 0) i--; while(i >= 0) { //flip the bit if(((num >> i) & 1) == 0) { ans |= 1 << i; } i--; } return ans; } }
- LeetCode - Letter Case Permutation
- LeetCode - XOR operation in an Array
- LeetCode - Find the Difference
- LeetCode - Number of steps to Reduce number to zero
- LeetCode - Binary Number with Alternating Bits
Comments
Post a Comment