简体   繁体   中英

Returning an integer whose digits sum exactly to n

My question is related to digits sum.

In a digit sum system, a digits sum of number 39 = 3 + 9 = 12.

However in my case, I would like to write a method where the user input 12, and the method will return 39, given that 39 is the smallest number to achieve digits sum of 12.

It will be good if we can discuss this in psuedo-code as I am more interested in learnign to develop a method/algorithm/formula to solve this puzzle.

The hint was given to use a queue. I have also tried the following:

number%9; number/9, which is close but does not seems to work for all cases.

An Example will be:

12%9 = 3

12/9 = 1; if( ans = 1, return 9)

therefore 3 and 9 will be 39. I know I am close but I tried using the same for numbers like 111, and this does not work anymore.

The smallest number is always of the form "x9...9999" where x is a single digit (possibly 0).

All you need to do is find:

  • The value of x: n % 9
  • How many 9s there are: n / 9 .

For 111:

  • n % 9 is 3.
  • n / 9 is 12.

So the answer is 3999999999999.

I think the smallest number n to have a digit sum equal to k will always be of the form

i99999

Where i is some digit.

Using this, you have

i = n % 9
j = floor(n / 9)

Then you construct your number by concatenating i then 9 j times.

For n = 12 this yields 39 .

For n = 111 this yields 3999999999999 (the 9 appears twelve times)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM