Given a string of numbers in sequence order. find the missing number.Range is not given.
sample input:"9899100101103104105"
Answer:102
Solution:
class FindMissingNumberInGivenString{
static int find(String str){
if(str == null || str.length() == 0)
return -1;
for(int i = 1; i < str.length()/2 ; i++){
int prevNum = getNumber(str, 0, i);
int offset = i;
while(true){
int nextA = prevNum + 1;
int lenA = getLength(nextA);
int nextB = prevNum + 2;
int lenB = getLength(nextB);
if(offset + lenA > str.length())
break;
int number = getNumber(str, offset, lenA);
if(number == nextA){
prevNum = nextA;
offset += lenA;
if(offset == str.length())
break;
continue;
}
if(offset + lenB > str.length())
break;
number = getNumber(str, offset, lenB);
if(number == nextB){ //found
return nextA;
}
break; //wrong sequence
}
}
return -1;
}
private static int getLength(int num) {
int len = 0;
while (num> 0){
num /= 10;
len++;
}
return len;
}
static int getNumber(String str, int i, int j){
return Integer.parseInt(str.substring(i, i+j));
}
public static void main(String ... args){
String str = "9899100101103";
System.out.println(find(str));
}
}
sample input:"9899100101103104105"
Answer:102
Solution:
class FindMissingNumberInGivenString{
static int find(String str){
if(str == null || str.length() == 0)
return -1;
for(int i = 1; i < str.length()/2 ; i++){
int prevNum = getNumber(str, 0, i);
int offset = i;
while(true){
int nextA = prevNum + 1;
int lenA = getLength(nextA);
int nextB = prevNum + 2;
int lenB = getLength(nextB);
if(offset + lenA > str.length())
break;
int number = getNumber(str, offset, lenA);
if(number == nextA){
prevNum = nextA;
offset += lenA;
if(offset == str.length())
break;
continue;
}
if(offset + lenB > str.length())
break;
number = getNumber(str, offset, lenB);
if(number == nextB){ //found
return nextA;
}
break; //wrong sequence
}
}
return -1;
}
private static int getLength(int num) {
int len = 0;
while (num> 0){
num /= 10;
len++;
}
return len;
}
static int getNumber(String str, int i, int j){
return Integer.parseInt(str.substring(i, i+j));
}
public static void main(String ... args){
String str = "9899100101103";
System.out.println(find(str));
}
}
No comments:
Post a Comment