educative.io

Educative

Same space & time but simpler

Isn’t the following solution simpler and of the same time and space complexity?

def calculate_bitwise_complement(n):
  result = 0
  current_bit = 1

  while current_bit <= n:
    if (n & current_bit) == 0:
      result += current_bit
    current_bit = current_bit << 1

  return result

The solution is good you can. change the approach if it is easy for you

my solution:

public static int bitwiseComplement(int n) {
  
  int noOfBits = (int) (Math.log(n)/Math.log(2)) + 1;
  int valueWithAllOnesFromNumOfBits = (int) Math.pow(2, noOfBits) -1;
  return n ^ valueWithAllOnesFromNumOfBits;
}

Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Complement of Base 10 Number (medium) - Grokking the Coding Interview: Patterns for Coding Questions