Here’s another easy problem which can be solved by applying logical operators.
class Solution {
fun findComplement(num: Int): Int {
return if(num == Integer.MAX_VALUE)
num xor Integer.MAX_VALUE
else {
var allOnes = 0
for(number in 0..31){
val p = Math.pow(2.0, number.toDouble()) - 1
if(p >= num) {
allOnes = p.toInt()
break
}
}
num xor allOnes.toInt()
}
}
}
Runtime: 124 ms, faster than 100.00% of Kotlin online submissions for Number Complement.
Memory Usage: 30.9 MB, less than 100.00% of Kotlin online submissions for Number Complement.
First, we have to find the first 2^n - 1 which is higher than the input number.
For example, if input is 5, the first 2^n-1 would be 7. In binary, 5 is 101 and 7 would be 111. Next, we apply exclusive OR to them to get the 1’s complement.