top of page
Caută
  • Poza scriitoruluioanaunciuleanu

Compute the sum of digits in all numbers from 1 to n in JAVA

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.


2 afișări0 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