【C++】Digit sum 2

本文介绍了一个编程问题,如何在C++中找到一个不超过给定整数N的正整数的最大十进制数码和。通过编写一个sum函数计算单个数字之和,然后使用while循环和条件判断找到最优解。
题目描述

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值