top of page
Caută
  • Poza scriitoruluioanaunciuleanu

Count of n digit numbers whose sum of digits equals to a given sum in JAVA

Starting from two received variables: digits and sum, find how many numbers having that amount of digits have the required sum of their digits.


Input: int digits = 2; int sum = 5; Output: 5 Explanation: The numbers whose sum of 2 digits is 5 are: 14, 23, 32, 41 and 50.



Solution:


1. private static int countToSum(int digits, int sum) { 2. int start = (int) Math.pow(10, digits - 1); 3. int end = (int) Math.pow(10, digits) - 1; 4. int count = 0; 5. int i = start; 6. 7. while (i < end) { 8. int current = 0; 9. int temporary = i; 10. 11. while (temporary != 0) { 12. current += temporary % 10; 13. temporary = temporary / 10; 14. } 15. 16. if (current == sum) { 17. count++; 18. i += 9; 19. } else { 20. i++; 21. } 22. } 23. return count; 24. } 25.

1 afișare0 comentarii

Postări recente

Afișează-le pe toate

Weighted Job Scheduling in JAVA

You receive a list of jobs that have three elements: start time, finish time and profit. You have to schedule the jobs with no overlapping, in order to obtain the maximum profit. Solution: 1. static

Tiling Problem in JAVA

You can use a board that is 2 x n size. The tiles are of size 2 x 1. Count the number of ways to tile the board. Tiles can be placed vertically 2 x 1 or horizontally as 1 x 2. Solution: 1. static

bottom of page