Enter a positive integer n and calculate 1 ~ The number of times 1 appears between n

Source: Internet
Author: User

[Cpp] // requirement: enter a positive integer n and calculate 1 ~ The number of times 1 appears between n # include <iostream> # include <math. h> using namespace std; void solve (); int input (); int power (int count); void main () {solve (); system ("pause ");} void solve () {int n, count = 0, I, sum = 0; n = input (); // count is a count to calculate the number of digits of n, for example, 1 is a single digit, and 2 is a hundred digits I = n; while (I) {I = I/10; count ++;} while (count --) {I = (n/power (count) % 10; // extracts the cout bit corresponding to count <I <endl; if (I = 1) {if (0 = count) // if the corresponding individual sum + = 1; else sum + = n % po Wer (count) + 1;} else if (I> 1) {sum + = power (count);} sum + = n/power (count + 1) * power (count);} cout <"One has" <sum <"1" <endl;} int input () {cout <"Enter the number you want to enter:" <endl; int n; cin> n; if (cin. fail () {cout <"your input is incorrect! "<Endl; exit (-1);} return n;} int power (int count) {int m = 1; if (count <0) {cout <"count value error! "<Endl; return-1;} else while (count --) m * = 10; return m;} I wrote the beautiful programming questions in my way and seldom read the source program, take a look at the train of thought at most. The complexity is O (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.