literal numbers small error.

hello i have a function that gets the amount of letters a number has when you write it litterally.
for example:
1->one->3 characters
15->fifteen->7 characters
i have to calculate the sum of the length of all numbers below 1000 and that should be 21124 and my output is 21151 so im doing something wrong but i don't find where. can someone tell me where i am going wrong ?
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <time.h>

int amount_of_letters(int i) {
	int letters[]={0,3,3,5,4,4,3,5,5,4};//0,1,2,3,4,5,6,7,8,9
	int letters2[]={3,6,6,8,8,7,7,9,8,8};//10,11,12,13,14,15,16,17,18,19
	int letters3[]={0,0,6,6,5,5,5,7,6,6};//00,10,20,30,40,50,60,70,80,90
	int letters4[]={7,11};//100,1000
	if (i<10) {
		return letters[i];
	} else if (i<20) {
		return letters2[i-10];
	} else if (i<100) {
		return letters3[(i-(i%10))/10]+letters[i%10];
	} else if (i<1000) {
		return letters[(i-(i%100))/100]+letters4[0]+3+amount_of_letters(i%100);
	} else if (i==1000) {
		return letters4[1];
	}
}

int main() {
	clock_t start, end;
	start = clock();
	int total=0;
	for (int i=1;i<1001;i++) {
		total=total+amount_of_letters(i);
	}
	std::cout<<total<<std::endl;
	end = clock();
	printf("\nTook %f seconds\n", (double)(end-start)/CLOCKS_PER_SEC);
	system("pause");
	return 0;
}
Last edited on
return letters[(i-(i%100))/100]+letters4[0]+3+amount_of_letters(i%100);
¿why are you adding 3 there?

By the way, integer division returns an integer so (i-(i%10))/10 == i/10
Topic archived. No new replies allowed.