0%

PAT A1049 Counting Ones

解题思路

从右到左看每一位的左右,考虑三种情况,0,1,和大于1。

我的代码

比较麻烦,使用right记录右边的位数,不如直接取余得好。

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
#include <cstdio>
#include <string>
#include <cmath>
using namespace std;
int n;

int main() {
scanf("%d", &n);
int ans=0,left=0,right=0,now;
int m=n;
now=n%10;
while(n!=0){
if(now==0){
left=n/10;
ans+=left*(int)pow(10,right);
}else if(now==1){
int l=n;
left=n/10;
left*=(int)pow(10,right);
ans+=left+1+m-l*(int)pow(10,right);
}else if(now>1){
left=n/10;
ans+=(left+1)*(int)pow(10,right);
}
n/=10;
now=n%10;
right++;//右边位数
}

printf("%d",ans);

return 0;
}

算法笔记代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <cstdio>
#include <string>
#include <cmath>

using namespace std;
int n;

int main() {
scanf("%d", &n);
int ans = 0, left = 0, right = 0, now, a = 1;
while (n / a != 0) {
left = n / (a * 10);
now = n / a % 10;
right = n % a;
if (now == 0) ans += left * a;
else if (now == 1) ans += left * a + right + 1;
else ans += (left + 1) * a;
a *= 10;
}

printf("%d", ans);

return 0;
}

本文标题:PAT A1049 Counting Ones

文章作者:GavinYGM

发布时间:2020年09月10日 - 18:09

最后更新:2020年09月10日 - 18:09

原始链接:http://www.gavinygm.cn/2020/09/10/PAT-A1049-Counting-Ones/

许可协议: 转载请保留原文链接及作者。