JAVA怎么用位运算求一个int的绝对值

dingzheng1989 2011-01-02 02:09:46
rt ,郁闷的是int是32位补码,试了半天竟想不出怎么办,大侠们帮我想想吧,谢谢了。(不要if-else)
...全文
746 17 打赏 收藏 转发到动态 举报
写回复
用AI写文章
17 条回复
切换为时间正序
请发表友善的回复…
发表回复
dingzheng1989 2011-01-22
  • 打赏
  • 举报
回复
[Quote=引用 16 楼 zhuzeitou 的回复:]

应该不是内存差异吧,你可以比较一下效率

从0x80000000(最小int型)到0x7fffffff(最大int型)循环执行,在我现在的机器上Math.abs需要5秒多,而#12和#13的代码(我只测试了这两个)都是2.4秒左右,#13的代码应该比我#12的更好,至少运算数要少一些
[/Quote] 学习 了
zhuzeitou 2011-01-05
  • 打赏
  • 举报
回复
应该不是内存差异吧,你可以比较一下效率

从0x80000000(最小int型)到0x7fffffff(最大int型)循环执行,在我现在的机器上Math.abs需要5秒多,而#12和#13的代码(我只测试了这两个)都是2.4秒左右,#13的代码应该比我#12的更好,至少运算数要少一些
william_unique 2011-01-03
  • 打赏
  • 举报
回复
3楼太金典了
guazixing 2011-01-03
  • 打赏
  • 举报
回复
i need score。。。
guazixing 2011-01-03
  • 打赏
  • 举报
回复
DAO。。。
uastation 2011-01-03
  • 打赏
  • 举报
回复
那就用三目运算符吧。
dingzheng1989 2011-01-03
  • 打赏
  • 举报
回复
谢谢各位,不过这个好你节省不了多少内存,唉。学习了就好。
dingzheng1989 2011-01-03
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 fclxyz 的回复:]

不知道这个问题有什么存在的价值,LZ把帖子结了吧……嘿嘿
[/Quote]我告诉你有什么价值吧,在每bt内存必争的手游开发中,位运算要比Math.abs节省巨多内存(特别是在线程中要不断的求绝对值的情况。)
singlark 2011-01-03
  • 打赏
  • 举报
回复

// 10> 取int型变量i的绝对值
public static int getABS(int i) {
int sign = i >> 31;
return (i + sign) ^ sign; // 或 (i ^ sign) - sign
}
zhuzeitou 2011-01-03
  • 打赏
  • 举报
回复
public static int abs(int i) {
int mask = i >> 31;
return (mask & (~i + 1)) | (~mask & i);
}
mtv0199 2011-01-03
  • 打赏
  • 举报
回复
public static int getABS(int i){
int tag = i>>>31;
int b = 0;
boolean bool = ((tag == 1) && (b == (i = (~(i - 1)))));
return i;
}

试一下吧~
  • 打赏
  • 举报
回复
Google: 位运算 绝对值
Leguroky 2011-01-02
  • 打赏
  • 举报
回复
负数的话,各位取反然后加+1就行了吧。不过要注意最小值没有对应的正数,还有就是0得考虑到。





Inhibitory 2011-01-02
  • 打赏
  • 举报
回复
public class Test {
public static void main(String[] args) {
System.out.println(abs(245));
System.out.println(abs(-245));
System.out.println(abs(1234213655));
System.out.println(abs(-1234213655));

System.out.println(abs(0));
System.out.printf("%32s\n", Integer.toBinaryString(0));

System.out.println(Integer.MAX_VALUE);
System.out.println(abs(Integer.MAX_VALUE));
System.out.printf("%32s\n", Integer.toBinaryString(Integer.MAX_VALUE));

System.out.println(Integer.MIN_VALUE + 1);
System.out.println(abs(Integer.MIN_VALUE + 1));
System.out.printf("%32s\n", Integer.toBinaryString(Integer.MIN_VALUE + 1));
}

public static int abs(int val) {
// 看上去是够累的
return (((val & (~0 << 31)) >>> 31) == 1) ? ((~val) + 1) & (~(~0 << 31)) : val;
}
}
fable0115 2011-01-02
  • 打赏
  • 举报
回复
不要ifesle
那三目运算可不可以
a>=0?a:-a
xuedianzhifeng 2011-01-02
  • 打赏
  • 举报
回复
路过 纯粹路过
tom_66 2011-01-02
  • 打赏
  • 举报
回复
不知道这个问题有什么存在的价值,LZ把帖子结了吧……嘿嘿

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧