Number Complement – Leetcode #476

Number Complement  -  Leetcode #476

Problem Statement

This problem is from Leetcode – Number Complement. The problem statement in short is as below:

Given an integer num, return its binary complement by flipping all 0s to 1s and all 1s to 0s in its binary representation.

Solution

This problem is simple enough. We first compute the binary of the given decimal and then get its complement. See the code sample below:

public int findComplement(int num) {
        
		// compute binary of given decimal
		String bin = Integer.toBinaryString(num);
		
		StringBuilder compStr = new StringBuilder();
		
		// compute complement of this binary
		for(int i=0; i<bin.length(); i++) {
			
			if(bin.charAt(i) == '0') {
				
				compStr = compStr.append('1');
			}
			
			if(bin.charAt(i) == '1') {
				
				compStr = compStr.append('0');
			}
		}	
		 
		// return corresponding decimal
		return Integer.parseInt(compStr.toString(),2);
    }

You can checkout the code from Github here: Number Complement. See the performance of this approach below:

PERFORMANCE ANALYSIS

RUNTIME1 ms | Beats 43.50 %
MEMORY40.14 MB | Beats 83.00 %
TIME COMPLEXITYO (N)

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top