给定数字N。任务是找到SumOfDigits(A)+ SumOfDigits(B)的最大可能值,以使A + B = n(0 <= A,B <= n)。
例子:
Input: N = 35
Output: 17
35 = 9 + 26
SumOfDigits(26) = 8, SumOfDigits(9) = 9
So, 17 is the answer.
Input: N = 7
Output: 7
方法:将数字分为A和B两部分,以使A等于9,即最接近N的数字,并且B = NA。例如,N = 35,最接近35的最小数字为29。
C++
// C++ implementation of above approach
#include
using namespace std;
// Returns sum of digits of x
int sumOfDigitsSingle(int x)
{
int ans = 0;
while (x) {
ans += x % 10;
x /= 10;
}
return ans;
}
// Returns closest number to x in terms of 9's.
int closest(int x)
{
int ans = 0;
while (ans * 10 + 9 <= x)
ans = ans * 10 + 9;
return ans;
}
int sumOfDigitsTwoParts(int N)
{
int A = closest(N);
return sumOfDigitsSingle(A) + sumOfDigitsSingle(N - A);
}
// Driver code
int main()
{
int N = 35;
cout << sumOfDigitsTwoParts(N);
return 0;
}
Java
// Java implementation of above approach
// Returns sum of digits of x
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
static int sumOfDigitsSingle(int x)
{
int ans = 0;
while (x != 0)
{
ans += x % 10;
x /= 10;
}
return ans;
}
// Returns closest number to x
// in terms of 9's.
static int closest(int x)
{
int ans = 0;
while (ans * 10 + 9 <= x)
ans = ans * 10 + 9;
return ans;
}
static int sumOfDigitsTwoParts(int N)
{
int A = closest(N);
return sumOfDigitsSingle(A) +
sumOfDigitsSingle(N - A);
}
// Driver code
public static void main(String args[])
{
int N = 35;
System.out.print(sumOfDigitsTwoParts(N));
}
}
// This code is contributed by
// Subhadeep Gupta
Python 3
# Python 3 implementation of above approach
# Returns sum of digits of x
def sumOfDigitsSingle(x) :
ans = 0
while x :
ans += x % 10
x //= 10
return ans
# Returns closest number to x in terms of 9's
def closest(x) :
ans = 0
while (ans * 10 + 9 <= x) :
ans = ans * 10 + 9
return ans
def sumOfDigitsTwoParts(N) :
A = closest(N)
return sumOfDigitsSingle(A) + sumOfDigitsSingle(N - A)
# Driver Code
if __name__ == "__main__" :
N = 35
print(sumOfDigitsTwoParts(N))
# This code is contributed by ANKITRAI1
C#
// C# implementation of above approach
// Returns sum of digits of x
using System;
class GFG
{
static int sumOfDigitsSingle(int x)
{
int ans = 0;
while (x != 0)
{
ans += x % 10;
x /= 10;
}
return ans;
}
// Returns closest number to x
// in terms of 9's.
static int closest(int x)
{
int ans = 0;
while (ans * 10 + 9 <= x)
ans = ans * 10 + 9;
return ans;
}
static int sumOfDigitsTwoParts(int N)
{
int A = closest(N);
return sumOfDigitsSingle(A) +
sumOfDigitsSingle(N - A);
}
// Driver code
public static void Main()
{
int N = 35;
Console.Write(sumOfDigitsTwoParts(N));
}
}
PHP
输出:
17