题目相关
题目链接
AtCoder Beginner Contest 187 A 题,https://atcoder.jp/contests/abc187/tasks/abc187_a。
Problem Statement
For an integer n n n, let S ( n ) S(n) S(n) be the sum of digits in the decimal notation of n n n. For example, we have S ( 123 ) = 1 + 2 + 3 = 6 S(123)=1+2+3=6 S(123)=1+2+3=6.
Given two 3 3 3-digit integers A A A and B B B, find the greater of S ( A ) S(A) S(A) and S ( B ) S(B) S(B).
Input
Input is given from Standard Input in the following format:
A B
Output
Print the value of the greater of S ( A ) S(A) S(A) and S ( B ) S(B) S(B).
If these are equal, print S ( A ) S(A) S(A).
Sample 1
Sample Input 1
123 234
Sample Output 1
9
Explaination
We have S ( 123 ) = 1 + 2 + 3 = 6 S(123)=1+2+3=6 S(123)=1+2+3=6 and S ( 234 ) = 2 + 3 + 4 = 9 S(234)=2+3+4=9 S(234)=2+3+4=9, so we should print the greater of these: 9 9 9.
Sample 2
Sample Input 2
100 999
Sample Output 2
27
Constraints
- All values in input are integers.
- 100 ≤ A , B ≤ 999 100 ≤ A, B ≤ 999 100≤A,B≤999
题解报告
题目翻译
给一个整数 n n n,我们定义 S ( n ) S(n) S(n) 为 n n n 的每一位总和。比如, S ( 123 ) = 1 + 2 + 3 = 6 S(123)=1+2+3=6 S(123)=1+2+3=6。
给两个三位整数 A A A 和 B B B,找出更大的 S ( A ) S(A) S(A) 和 S ( B ) S(B) S(B)。
题目分析
还是老配方,一个签到题。当然本题不是最简单的语法签到题。本题的考点就是如何实现 S ( A ) S(A) S(A) 的功能,其实就是将任意数字的每一位取出。
S(A)
学习过 C + + C++ C++ 循环语法的,应该都可以实现。我们通过取模和整除功能,就可以实现。
int S(int a) {
int ans=0;
while (0!=a) {
ans += a%10;
a /= 10;
}
return ans;
}
当然本题非常的特殊,题目告诉我们,保证 A A A 和 B B B 是三位数字。因此可以直接使用取模加整除来实现。
int S(int a) {
int gw = a%10;
int sw = a/10%10;
int bw = a/100%10;
return gw+sw+bw;
}
数据规模分析
最大的三位数为 999 999 999,因此 S ( 999 ) = 9 + 9 + 9 = 27 S(999)=9+9+9=27 S(999)=9+9+9=27。用 int 足够。
AC 参考代码
//https://atcoder.jp/contests/abc187/tasks/abc187_a
//A - Large Digits
#include <bits/stdc++.h>
using namespace std;
//如果提交到OJ,不要定义 __LOCAL
//#define __LOCAL
int sum(int x) {
int ans=0;
while (x) {
ans+=x%10;
x/=10;
}
return ans;
}
int main() {
#ifndef __LOCAL
//这部分代码需要提交到OJ,本地调试不使用
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
#endif
int a,b;
cin>>a>>b;
//
int ans0=sum(a);
int ans1=sum(b);
if (ans0>=ans1) {
cout<<ans0<<"\n";
} else {
cout<<ans1<<"\n";
}
#ifdef __LOCAL
//这部分代码不需要提交到OJ,本地调试使用
system("pause");
#endif
return 0;
}
时间复杂度
O(1)。
空间复杂度
O(1)。