Solution One:
int numberof1between1andn (unsigned int n)
{
int number = 0;
for (unsigned int i = 1; I <= n; ++i)
Number + = NUMBEROF1 (i);
return number;
}
int NumberOf1 (unsigned int n)
{
int number = 0;
while (n)
{
if (n% 10 = = 1)
number++;
n = N/10;
}
return number;
}
The solution of improving the time efficiency from the digital law
int numberof1between1andn (int n)
{
if (n <= 0)
return 0;
Char strn[50];
sprintf (StrN, "%d", n);
Return NumberOf1 (StrN);
}
int NumberOf1 (const char* StrN)
{
if (!strn | | *strn < ' 0 ' | | *strn> ' 9 ' | | *strn = = ' + ')
return 0;
int first = *STRN-' 0 ';
unsigned int length = static_cast<unsigned int> (strlen (StrN));
if (length = = 1 && first = = 0)
return 0;
if (length = = 1 && First > 0)
return 1;
Suppose Strn is 21345.
Numfirstdigit is the number of digits in the first bit of a number 10000~19999
int numfirstdigit = 0;
if (First > 1)
Numfirstdigit = PowerBase10 (length-1);
else if (first = = 1)
Numfirstdigit = atoi (StrN + 1) + 1;////+1 Remove the highest bit, plus 1
Numbotherdigits is the number of digits in the 1346~21345 except the first digit.
int numotherdigits = first* (length-1) *powerbase10 (length-2);//A random selection from the length-1 bit, the remaining length-2 bit is a combination of 0~9
Numrecursive is the number in 1~1345
int numrecursive = NUMBEROF1 (StrN + 1);//Remove Highest bit
Return numfirstdigit + numotherdigits + numrecursive;
}
int PowerBase10 (unsigned int n)
{
int result = 1;
for (unsigned int i = 0; i < n; ++i)
result*= 10;
return result;
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Number of occurrences of 1 in integers from 1 to n