判断一个数的正负

程序

public class Zf0Algorithm {

    public static void main(String[] args) {
        System.out.println(zf0(13));
        System.out.println(zf0(0));
        System.out.println(zf0(-25));
    }

    public static int zf0(int num) {
        return (num>>31)|(-num>>>31);
    }
}

输出

 1  #test num 13
 0  #test num 0
-1  #test num -25

核心思想

num b31(符号位) …b30~b1… b0
1 0 0 1
0 0 0 0
-1 1 0 0
操作 正数 负数
num>>31 0…0…0 0…0…0 1…0…0
-num>>>31 0…0…1 0…0…0 0…0…0
or 0…0…1 0…0…0 1…0…0
结果 1 0 -1

猜你喜欢

转载自blog.csdn.net/qingguang686/article/details/112301414