Iroh
Iroh

Reputation: 5

Smallest number whose sum of the digits is equal to the given number n

Below statement gives smallest number whose sum of digit is equal to the given number n. If the input is 10 output will be 19 (1+9=10)

digits=(c % 9 + 1) * pow(10, (c / 9)) - 1

But when the input is greater like 100000, the output shows Inf. Can anyone help me to solve this, I even tried with unsigned long long int.

Upvotes: 0

Views: 5786

Answers (1)

selbie
selbie

Reputation: 104514

Assuming you just want to print the answer and not keep it stored in an integer variable, you can avoid overflow by taking the first digit as c%9and append c/9 number of '9' chars to complete the summation.

std::string getDigits(long long c)
{
    if (c == 0)
    {
        return "0";
    }

    if (c < 0)
    {
        return "";
    }

    auto first = (c % 9);
    c -= first;
    auto nineCount = c / 9;

    std::string result;

    if (first != 0)
    {
        result += std::string(1, (char)(first+'0'));
    }

    result += std::string(nineCount, '9');

    return result;
}

Example run:

int main()
{
    std::cout << getDigits(987) << std::endl;
    return 0;
}

prints:

69999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999

Upvotes: 1

Related Questions