Java Algorithms How to - Convert positive int to negative and negative to positive








Question

We would like to know how to convert positive int to negative and negative to positive.

Answer

/*  www . j  a va 2s . co  m*/
public class Main {
  public static void main(String[] args) throws java.lang.Exception {
    int iPositive = 15;
    int iNegative = (~(iPositive - 1)); 
    
    System.out.println(iNegative);

    iPositive = ~(iNegative - 1);
    System.out.println(iPositive);

    iNegative = 0;
    iPositive = ~(iNegative - 1);
    System.out.println(iPositive);
  }
}

The code above generates the following result.