日期:2014-05-20  浏览次数:20848 次

如何求一个int型数的绝对值?
问题如题:

要求:

1、不得使用任何API,如Math.abs()等。
2、不得使用判断语句,如if、for、while、switch、?:等。
3、不得使用比较语句,如:==、<=、>=、!=、<、>等。

请看清要求。

------解决方案--------------------
i = (1 - (i>>>31)) * i - (i>>>31) * i
------解决方案--------------------
探讨
int i=-2
i=i&0x7fffffff

------解决方案--------------------
贴好看点。。。
Java code

public class TestAbs {
    public static void main(String args[]){
        int temp = - 8;
        int out = temp;
        temp = temp >> 31;
        out = out ^ temp;
        out = out - temp;
        System.out.println(out);
    }
}

------解决方案--------------------
Java code
  public static int abs(int num) {
    return num * (1 - ((num >>> 31)<<1));
  }

------解决方案--------------------
1,3,13楼的一样的.

类似的还有:num*(1-((num&0X80000000)>>>30))

略有不同的是:
(num^-(num>>>31))+(num>>>31)