Java math function to convert positive int to negative and negative to positive?

后端 未结 13 2169
暗喜
暗喜 2020-12-01 04:29

Is there a Java function to convert a positive int to a negative one and a negative int to a positive one?

I\'m looking for a reverse function to perfor

13条回答
  •  粉色の甜心
    2020-12-01 04:52

    Another method (2's complement):

    public int reverse(int x){
        x~=x;
        x++;
        return x;
    }
    

    It does a one's complement first (by complementing all the bits) and then adds 1 to x. This method does the job as well.

    Note: This method is written in Java, and will be similar to a lot of other languages

提交回复
热议问题