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.
Comments