You are given a limit and have to find the sum of all numbers from one to that limit.
Input: int limit = 8; Output: 36 Explanation: The sum of numbers 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36. |
Solution:
1. static int sumOfDigitsFrom1ToN(int limit) { 2. int digits = (int) (Math.log10(limit)); 3. int[] values = new int[digits + 1]; 4. values[0] = 0; 5. if (digits > 0) { 6. values[1] = 45; 7. } 8. for (int i = 2; i <= digits; i++) { 9. values[i] = values[i - 1] * 10 + 45 * (int) (Math.ceil(Math.pow(10, i - 1))); 10. } 11. 12. return computeDigits(limit, values); 13. } 14. 15. static int computeDigits(int limit, int[] values) { 16. if (limit < 10) { 17. return (limit * (limit + 1) / 2); 18. } 19. 20. int digits = (int) (Math.log10(limit)); 21. int power = (int) (Math.ceil(Math.pow(10, digits))); 22. int mostSignificantDigit = limit / power; 23. return (mostSignificantDigit * values[digits] + (mostSignificantDigit * (mostSignificantDigit - 1) / 2) * power + mostSignificantDigit * (1 + limit % power) + computeDigits(limit % power, values)); 24. } 25.
Comments