题目地址:
https://www.lintcode.com/problem/next-smaller-and-larger-number-with-the-same-1-bits/description
给定一个正整数 n n n,将其看成二进制正整数,求最小的比其大的数满足和 n n n里 1 1 1的位数一样多,再求最大的比其小的数满足和 n n n里 1 1 1的位数一样多。需要在 32 32 32位整数的范围内寻找,如果找不到则返回 − 1 -1 −1。
其实是Next Permutation和Previous Permutation问题的变种。Next Permutation思路参考https://blog.csdn.net/qq_46105170/article/details/108460153,Previous Permutation思路参考https://blog.csdn.net/qq_46105170/article/details/108543529。这个问题本身需要注意,在找更大数的时候有可能溢出,可以用long来解决。代码如下:
public class Solution {
/*
* @param n: a positive integer
* @return: a positive integer or -1
*/
public int getPrev(int n) {
// write your code here
char[] num = Integer.toBinaryString(n).toCharArray();
int i = num.length - 1;
while (i > 0 && num[i - 1] <= num[i]) {
i--;
}
if (i == 0) {
return -1;
}
int j = num.length - 1;
while (j > 0 && num[j] == '1') {
j--;
}
swap(num, i - 1, j);
reverse(num, i, num.length - 1);
return Integer.parseInt(new String(num), 2);
}
/*
* @param n: a positive integer
* @return: a positive integer or -1
*/
public int getNext(int n) {
// write your code here
char[] num = ("0" + Integer.toBinaryString(n)).toCharArray();
int i = num.length - 1;
while (i > 0 && num[i - 1] >= num[i]) {
i--;
}
int j = num.length - 1;
while (j > 0 && num[j] == '0') {
j--;
}
swap(num, i - 1, j);
reverse(num, i, num.length - 1);
// 这里有可能溢出,需要用long来接
long res = Long.parseLong(new String(num), 2);
return res > Integer.MAX_VALUE ? -1 : (int) res;
}
private void swap(char[] str, int i, int j) {
char tmp = str[i];
str[i] = str[j];
str[j] = tmp;
}
private void reverse(char[] str, int i, int j) {
while (i < j) {
swap(str, i, j);
i++;
j--;
}
}
}
时空复杂度 O ( 1 ) O(1) O(1)。