题目描述
Find the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.
Constraints
1≤N≤1016
N is an integer.
输入
Input is given from Standard Input in the following format:
N
输出
Print the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.
样例输入 Copy
100
样例输出 Copy
18
提示
For example, the sum of the digits in 99 is 18, which turns out to be the maximum value.
#include <bits/stdc++.h> using namespace std; typedef long long LL; int sum(LL x) { int ans = 0; long long temp = x; while (x) { ans += x % 10; x /= 10; } return ans; } int main() { LL n; cin >> n; int s = sum(n); LL temp = n, w = 1; while (temp >= 10) { temp /= 10; w *= 10; } cout << max(s, sum(n / w * w - 1)) << '\n'; return 0; }
本文介绍了一个编程问题,如何在C++中找到一个不超过给定整数N的正整数的最大十进制数码和。通过编写一个sum函数计算单个数字之和,然后使用while循环和条件判断找到最优解。
184

被折叠的 条评论
为什么被折叠?



