# Complement of Base 10 Integer - LeetCode

Created by Piyush Garg about a year ago

0

No description

0

SUperb

@safrin

0

Hi Piyush

when we face this type of questions for the first time or for any new questions, how I came to know that I should use MASKing here or I should use ANDing between MASK and ~n in this question ?

Parth Trivedi

@parthtrivedi

2

Masking is cool!! but, here is my alternate approach without masking: class Solution { public int bitwiseComplement(int n) { int res = 0; int index = 0; if (n == 0){ res = 1; } else { while (n != 0){ int lastBit = n & 1; if (lastBit == 0){ // since we are complementing check for 0 bits res = res + (int) Math.pow(2, index); } n = n >> 1; index += 1; } } return res; } }

Gaurav Chindarkar

@grvvv

1

I tried this solution before watching the video and came up with this one I am just doing the xor with last bit and rest is similar to converting binary to decimal. Why exactly do we need mask and in which cases would it be useful class Solution { public int bitwiseComplement(int n) { if(n == 0) return 1; int result = 0; int index = 0; while(n != 0) { int lastBit = (n & 1) ^ 1; if(lastBit == 1) { result = result + (int)Math.pow(2, index); } n = n >>> 1; ++index; } return result; } }

Aman Dhurwey

@amandhurwey