leet-code/src/main/java/leetcode/editor/cn/ReverseBits.java
huangge1199@hotmail.com e3685e9583 190:颠倒二进制位
2021-07-19 23:04:08 +08:00

85 lines
2.7 KiB
Java
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//颠倒给定的 32 位无符号整数的二进制位。
//
//
//
// 提示:
//
//
// 请注意,在某些语言(如 Java没有无符号整数类型。在这种情况下输入和输出都将被指定为有符号整数类型并且不应影响您的实现因为无论整数是有符号的
//还是无符号的,其内部的二进制表示形式都是相同的。
// 在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在上面的 示例 2 中,输入表示有符号整数 -3输出表示有符号整数 -10737418
//25。
//
//
//
//
// 进阶:
//如果多次调用这个函数,你将如何优化你的算法?
//
//
//
// 示例 1
//
//
//输入: 00000010100101000001111010011100
//输出: 00111001011110000010100101000000
//解释: 输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596
// 因此返回 964176192其二进制表示形式为 00111001011110000010100101000000。
//
// 示例 2
//
//
//输入11111111111111111111111111111101
//输出10111111111111111111111111111111
//解释:输入的二进制串 11111111111111111111111111111101 表示无符号整数 4294967293
//  因此返回 3221225471 其二进制表示形式为 10111111111111111111111111111111 。
//
// 示例 1
//
//
//输入n = 00000010100101000001111010011100
//输出964176192 (00111001011110000010100101000000)
//解释:输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596
// 因此返回 964176192其二进制表示形式为 00111001011110000010100101000000。
//
// 示例 2
//
//
//输入n = 11111111111111111111111111111101
//输出3221225471 (10111111111111111111111111111111)
//解释:输入的二进制串 11111111111111111111111111111101 表示无符号整数 4294967293
//   因此返回 3221225471 其二进制表示形式为 10111111111111111111111111111111 。
//
//
//
// 提示:
//
//
// 输入是一个长度为 32 的二进制字符串
//
// Related Topics 位运算 分治
// 👍 410 👎 0
package leetcode.editor.cn;
//190:颠倒二进制位
class ReverseBits{
public static void main(String[] args) {
//测试代码
Solution solution = new ReverseBits().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int result = 0;
for (int i = 0; i < 32 && n != 0; ++i) {
result |= (n & 1) << (31 - i);
n >>>= 1;
}
return result;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}