-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path43_Numbers_Of_1.cpp
More file actions
70 lines (51 loc) · 1.02 KB
/
43_Numbers_Of_1.cpp
File metadata and controls
70 lines (51 loc) · 1.02 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//
// Created by mark on 2019/7/19.
// Copyright © 2019年 mark. All rights reserved.
//
/*
说明:
1. 问题:43.求1~n的所有整数中1出现的次数
2. 思路:1. 不断对每个数字分解
2. 找规律
*/
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <cmath>
#include <string>
#include <assert.h>
#include <cstdio>
#include <fstream>
#include <map>
#include <set>
using namespace std;
int NumberOf1(unsigned int n);
// 方法1.不断对每个数字分解
int NumberOf1_sum(unsigned int n)
{
int sum = 0;
for(int i = 1; i <= n; i++)
sum += NumberOf1(i);
return sum;
}
// 求每个数字中1的个数
int NumberOf1(unsigned int n)
{
int sum = 0;
while(n)
{
if(n % 10 == 1)
sum++;
n /= 10;
}
return sum;
}
int main()
{
cout << "输入数字:";
int num;
cin >> num;
cout << "1~" << num << "中1的个数是:" << NumberOf1_sum(num) << endl;
return 0;
}