Write a program to subtract one from a given number. The use of operators like ‘+’, ‘-‘, ‘*’, ‘/’, ‘++’, ‘–‘ …etc are not allowed.
Examples:
Input: 12 Output: 11 Input: 6 Output: 5
Method 1
To subtract 1 from a number x (say 0011001000), flip all the bits after the rightmost 1 bit (we get 0011001111). Finally, flip the rightmost 1 bit also (we get 0011000111) to get the answer.
- Java
// Java code to subtract
// one from a given number
import java.io.*;
class GFG
{
static int subtractOne( int x)
{
int m = 1 ;
// Flip all the set bits
// until we find a 1
while (!((x & m) > 0 ))
{
x = x ^ m;
m <<= 1 ;
}
// flip the rightmost
// 1 bit
x = x ^ m;
return x;
}
// Driver Code
public static void main (String[] args)
{
System.out.println(subtractOne( 13 ));
}
}
Output:
12