-1

In C++, 1 is treated as true and 0 is treated as false. So, internal conversion is possible in C++. But can this be possible in Java? Can we convert int to boolean or boolean into int as per our need in Java?

For Example, for this problem on GeeksForGeeks, the C++ code might look like -

class Solution {
    public:
        int findPosition(int N) {
            if((N & (N -1)) or (N == 0)) return -1;
            return log2(N) + 1;
        }
};

How can write the same type of solution in Java? Thank You.

Botje
  • 26,269
  • 3
  • 31
  • 41

1 Answers1

1

C++ implicitly converts int to boolean. In Java, you will have to do that explicitly by yourself. To convert an int to boolean, just check whether it's not zero like this: N != 0

So you have to modify your original expression to something like this:

if (((N & (N - 1)) != 0) || (N == 0))

Vice versa, to convert a boolean to an int, do something like this: int i = boolValue ? 1 : 0;

off99555
  • 3,797
  • 3
  • 37
  • 49
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770