I strongly advice looking into the math of your problem and come up with a clever algorithm that you then implement. The 1s are far from randomly distributed in a range of numbers that are count up 😉
However there is always the brute force approach.
(This is just to show a possibility and one of the worst ways to solve the problem)
int count = 0;
for(int i = 1; i<=11; i++)
{
String number = String.valueOf(i);
while(number.contains("1"))
{
number= number.substring(number.indexOf("1")+1);
count ++;
}
}
System.out.println(count);
EDIT:
For those with an interest in better brute force version using log, mod and div (best I could come up with yet ^^):
int count2 = 0;
for(int i = lowerbound; i<=upperbound; i++)
{
int temp = Math.abs(i); //make positive. No negative log
if(temp==0) //beware the log(0) trap
continue;
int length = (int)(Math.log10(temp)+1); //count digits
for(int j = length -1; j>=0 ; j--) //inspect digit for digit
{
if(temp % 10 == 1)
{
count2 ++;
}
temp = temp / 10;
}
}
Tests done with a range from -1000000 to 1000000 measured with nano() (so no units). For CharAt approach see Tom Wellbrock s answer.
Even though log, % and / are quite slow mathematical operations the cost for a String creation is more expensive.
Without java Optimisation: :
- SubString: 14000002 time taken:
- 18351768293
- Log: 14000002 time taken:
- 2895089202
- CharAt: 14000002 time taken:
- 13929667983
With java optimisation (creating Strings becomes a lot cheaper then, especially when they appear twice and all the little tweaks why we love java so much)
- SubString:14000002 time taken:
- 1088103359
- Log:14000002 time taken:
- 568686169
- CharAt:14000002 time taken:
- 741721424
2
solved Write a program which accepts two integers as a minimum and maximum limit and calculates total of how many 1s were their within the limit