Number of occurrences of 1 in integers from 1 to n

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.