Home > Net >  The total number of digits between two numbers
The total number of digits between two numbers

Time:10-03

I am working on a program right now and part of it requires me to find the total amount of digits between two integers, I have figured it out for integers that have the same amount of digits, e.g. 1234 and 4980 (both have four digits) but I can't seem to figure it out for the integers that don't have the same amount of digits, i.e. 3 and 5698 (3 only has one digit and 5698 has four). How might I go about this?

CodePudding user response:

Boy, the algorithm is not obvious – your last comment is rather crucial.

Evidently this question boils down to:

  • For each 'number' between the 2, including both of the edges, count how many digits that number has.
  • Sum those up.

For your example it's simply (4980 - 1234 1) * 4 = 14988.

Sounds like you simply need to for-loop: for (int i = 1234; i <= 4980; i ), and then for each i just figure out how many digits there are and add those.

CodePudding user response:

An straightforward way is to use logarithms. The number of digits in an integer n is (int)Math.log10(n) 1. Assuming you are doing inclusive computations on first thru last it would be as follows:


int sum = 0;
int first = 3;
int last = 3333;
for (int i = first; i <= last; i  ) {
    sum  = Math.log10(i) 1;
}
System.out.println(sum);

prints

12223

But a more efficient and perhaps less obvious way it to forgo logs and simply compute in pieces. This will reduce number of iterations of the loop. This works by computing the number of digits and the power in increments. I put in print statements so you can see the progression.

int digits = 1;
int power = 10;
int limit = last;
sum = 0;
while(power < limit) {
    if (power > first) {
        sum  = (power - first) * digits;
        System.out.println(power   " "   first    " "   digits   " : partial running sum = "   sum);
        first = power;
    }
    
    digits  ;
    power*= 10;
}
sum  = (limit - power/10   1)*digits;
System.out.println(limit   " "   power/10    " "   digits   " : partial running sum = "   sum);
System.out.println(sum);

prints

10 3 1 : partial running sum = 7
100 10 2 : partial running sum = 187
1000 100 3 : partial running sum = 2887
3333 1000 4 : final sum = 12223
12223
  •  Tags:  
  • java
  • Related