每次取最低位 加在中间结果的上面 然后把中间结果左移一位 除了最后一次不用左移
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int res = 0;
for ( int i = 1; i <= 32; i ++ ){
res += n & 1;
n >>>= 1;
if ( i <= 31 )
res <<= 1;
}
return res;
}
}

本文介绍了一个使用Java实现的整数反转算法,通过位操作技巧将整数的最低位逐次移至最高位,实现整数的逆序。代码简洁高效,适合初学者理解和实践。
677

被折叠的 条评论
为什么被折叠?



