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);
}
}
求大于A的最大不重复数
最新推荐文章于 2022-11-28 15:26:29 发布