首页 > 其他 > 详细

-2147483648的绝对值

时间:2020-07-05 23:38:53      阅读:84      评论:0      收藏:0      [点我收藏+]

求整型绝对值的有以下方法:

  1. int abs = a > 0 ? a : -a;
  2. Math.abs()函数

以int整型为例,取值范围是-2147483648 ~ 2147483647,对于-2147483647 ~ 2147483647范围内的数字,使用上面的方法没有问题,但是对于-2147483648 取绝对值的时候却会直接返回该值。

以下是Java中Math.abs()函数的源码

/**
 * Returns the absolute value of an {@code int} value.
 * If the argument is not negative, the argument is returned.
 * If the argument is negative, the negation of the argument is returned.
 *
 * <p>Note that if the argument is equal to the value of
 * {@link Integer#MIN_VALUE}, the most negative representable
 * {@code int} value, the result is that same value, which is
 * negative.
 *
 * @param   a   the argument whose absolute value is to be determined
 * @return  the absolute value of the argument.
*/
public static int abs(int a) {
    return (a < 0) ? -a : a;
}

/**
 * Returns the absolute value of a {@code long} value.
 * If the argument is not negative, the argument is returned.
 * If the argument is negative, the negation of the argument is returned.
 *
 * <p>Note that if the argument is equal to the value of
 * {@link Long#MIN_VALUE}, the most negative representable
 * {@code long} value, the result is that same value, which
 * is negative.
 *
 * @param   a   the argument whose absolute value is to be determined
 * @return  the absolute value of the argument.
 */
public static long abs(long a) {
    return (a < 0) ? -a : a;
}

下面是各个值的二进制:

二进制
-2147483647原码 1111 1111 1111 1111 1111 1111 1111 1111
-2147483647补码 1000 0000 0000 0000 0000 0000 0000 0001
-1原码 1000 0000 0000 0000 0000 0000 0000 0001
-1补码 1111 1111 1111 1111 1111 1111 1111 1111
-2147483648 补码 1000 0000 0000 0000 0000 0000 0000 0000

-2147483648的绝对值

原文:https://www.cnblogs.com/cdbb/p/13252034.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!