【Lintcode】233. Next Smaller and Larger Number with the Same 1 Bits

题目地址:

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值