求大于A的最大不重复数

package chow;

/**
 * 有道难题,如果一个数字十进制表达时,不存在连续两位数字相等,
 * 则称之为“不重复数”。例如,105,1234和12121都是“不重复数”,
 * 而11,100和 1225不算。给定一个long类型数字A,返回大于A的最小“不重复数”。
 * @author chow
 * @date 2010-6-30
 */

public class NoRepetionNum {
    public static void main(String[] args){
        System.out.println("result: " + checkRepeatNum(54));
        System.out.println("result: " + checkRepeatNum(10));
        System.out.println("result: " + checkRepeatNum(9));
        System.out.println("result: " + checkRepeatNum(98));
        System.out.println("result: " + checkRepeatNum(21099));
        System.out.println("result: " + checkRepeatNum(99123));
        System.out.println("result: " + checkRepeatNum(1134567));
    }
   
    //返回第一对重复的数的第二位的位置,如没重复数返回-1
    public static int firstRepeatIndex(long num){
        String strNum = String.valueOf(num);
        int index = 0;
        while(index < strNum.length() - 1){
            if(strNum.charAt(index) == strNum.charAt(index + 1)){
                return index + 1;
            }
            index++;
        }
        return -1;
    }
   
    //返回大于Num的最小:不重复数
    public static long checkRepeatNum(long num){
        num++;
        String strNum = String.valueOf(num);
        int index = -1;
        while((index = firstRepeatIndex(Long.parseLong(strNum))) != -1){
            String toAdd = strNum.substring(0, index + 1);
            String newPre = String.valueOf(Long.parseLong(toAdd) + 1);
            strNum = newPre + strNum.substring(index + 1, strNum.length());
//            System.out.println(strNum);
            //有进位
            if(newPre.length() > toAdd.length()){
                continue;
            }else{
                //把剩余位换成0,1相间
                int tmp = 0;
                while(index < strNum.length() - 1){
                    newPre = newPre + tmp;
                    tmp ^= 1;
                    index++;
                }
                strNum = newPre;
                break;
            }
        }
        return Long.parseLong(strNum);
    }
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值