wdd
BAN USERThis works for all two digit number sequences, but things start falling apart after that. Specifically, all tests pass until index 191, but not beyond.
Does anyone have suggestions?
public class IndexOnInfiiniteNumber {
public static void main(String args[]) {
int idx = 1000;
System.out.println("Answer must be: " + verifier(idx));
System.out.println("Actual Answer is: " + calcNumberAtIndex(idx));
}
public static char verifier(int idx) {
String str = "";
int count = 0;
if (idx < 0) {
throw new RuntimeException("Can not be a negative number");
}
while (str.length() <= idx) {
str += count++;
}
for (int i = 0; i < str.length(); i++) {
System.out.println(i + "->" + str.charAt(i));
}
return str.charAt(idx);
}
public static long calcNumberAtIndex(long idx) {
if (idx < 0) {
throw new RuntimeException("Index can not be negative");
}
if (idx < 10) {
return idx;
}
long distanceFrom10 = (idx - 10) / 2;
long number = 10 + distanceFrom10;
System.out.println("Number at index calc as: " + number);
long numDigits = howManyDigits(number);
long factor = (long) Math.pow(10, numDigits - 1);
if (idx % 2 == 0) {
return number / factor;
} else {
return number - ((number / factor) * factor);
}
}
public static long howManyDigits(long number) {
long numDigits = 1;
if (number < 0) {
number = number * -1;
}
while (number >= 10) {
number = number / 10;
numDigits++;
}
return numDigits;
}
}
brilliant dude
- wdd February 04, 2013