Kevin Helma :
I've made a simple code to count the occurrences of the digit '14' from a given number. I've successfully print out the counter if the given number is 10 000 000 and it took less than 1 second. When i increase the number to 10 000 000 000 it took 459 seconds. Any ideas on how to make it runs faster?
long startTime = System.nanoTime();
long counter = 0L;
for (long i = 14; i <= 10000000000L; i++)
{
String s = Long.toString(i);//i.ToString();
if (s.contains("14"))
{
counter += 1;
}
}
long endTime = System.nanoTime();
long totalTime = endTime - startTime;
long convert = TimeUnit.SECONDS.convert(totalTime, TimeUnit.NANOSECONDS);
System.out.println(convert + " seconds");
System.out.println(counter);
time taken : 459 seconds
number of 14 appears : 872348501
Andy Turner :
The most obvious optimization: don't construct strings.
Just check the last two digits of the number, and then divide by 10 until you find a 14:
boolean matches = false;
for (long num = i; num >= 14 && !matches; num /= 10) {
matches = (num % 100) == 14;
}
if (matches) {
counter += 1;
}
But, you would likely just be able to calculate the number of cases, using the inclusion/exclusion principle.