If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.
1~1000을 영어로 작성했을 때의 글자 개수를 구하는 문제. 단, 띄어쓰기, 하이픈( - )은 집계에서 제외한다.
영어의 경우 글자의 구분은 다음과 같이 이루어진다.
1~19 - 각각 고유 명칭이 있으므로 해당 명칭으로 처리. 20~99 - 십의 자리 + 일의 자리. 단, 일의 자리가 0일 경우에는 생략. 100~999은 1~9 + hundred + 1~99
1000은 1 + thousand ...
각 명칭에 해당하는 글자 수를 결과 변수에 더해주면 된다.
int getLetterCount(const int number)
{
switch (number)
{
case 0: return 0;
case 1: return 3;
case 2: return 3;
case 3: return 5;
case 4: return 4;
case 5: return 4;
case 6: return 3;
case 7: return 5;
case 8: return 5;
case 9: return 4;
case 10: return 3;
case 11: return 6;
case 12: return 6;
case 13: return 8;
case 14: return 8;
case 15: return 7;
case 16: return 7;
case 17: return 9;
case 18: return 8;
case 19: return 8;
case 20: return 6;
case 30: return 6;
case 40: return 5;
case 50: return 5;
case 60: return 5;
case 70: return 7;
case 80: return 6;
case 90: return 6;
case 100: return 7;
case 1000: return 8;
default: return -1;
}
}
int Problem017(const int scope)
{
int ret = 0;
for (int i = 1; i <= scope; i++)
{
int current = i;
if (current >= 1000)
{
ret += getLetterCount(current / 1000);
ret += getLetterCount(1000);
current %= 1000;
}
if (current >= 100)
{
ret += getLetterCount(current / 100);
ret += getLetterCount(100);
current %= 100;
if (current != 0)
{
ret += 3; // and
}
}
if (current >= 21)
{
ret += getLetterCount((current / 10) * 10);
ret += getLetterCount(current % 10);
}
else if (current > 0)
{
ret += getLetterCount(current);
}
}
return ret;
}
215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 21000?
2의 1000제곱의 각 자리 수를 모두 더할 경우 몇이 되는지 구하는 문제. 1. 필요한 만큼 배열을 할당한다. 2. 아래에 기술한 내용을 지수만큼 반복한다. - 배열 각 요소에 2를 곱한다. - 값이 10 이상인 요소는 다음 자리에 10을 나눈 몫을 더해주고 나머지만 남긴다. 3. 배열에 있는 각 요소의 값을 모두 더한다.
int Problem016(int exponent)
{
if (exponent < 0)
{
return -1;
}
if (exponent == 0)
{
return 1;
}
int * arrNum = new int[exponent + 1];
arrNum[0] = 1;
for (int i = 1; i <= exponent; i++)
{
arrNum[i] = 0;
}
for(int i = 1; i <= exponent; i++)
{
for (int j = 0; j < exponent; j++)
{
if (arrNum[j] == 0)
{
continue;
}
arrNum[j] *= 2;
}
for (int k = 0; k <= exponent; k++)
{
if (arrNum[k] == 0)
{
continue;
}
if (arrNum[k] >= 10)
{
arrNum[k + 1] += arrNum[k]/10;
arrNum[k] %= 10;
}
}
}
int ret = 0;
for (int i = exponent; i >= 0; i--)
{
ret += arrNum[i];
}
return ret;
}