简体   繁体   中英

Adding numbers digits to number

For my program, I'd want to code an array 1-100. In that array, I want to store the number + their digits. For example, if the number is 6 the stored value would be 6 because of 6 + 6 = 12. If the number is 17 the stored value should be 25 because 17 + 1 + 7 = 25. I want to do it for every number. My code has a method and 2 for loops but currently outputs everything as 0; Here's my code.

public class GeneratedNums {

public static void main(String[] args) {

    int [] numbers = new int [101]; 

    for ( int x=0; x < 101; x++){
        numbers[x] = sumDigits (x);


    }

    for ( int x=0; x < numbers.length; x++){
        System.out.println(x + ": " + numbers[x]);
    }


}

public static int sumDigits ( int num) {

   int sum = num;

   while ( num != 0){
       num += num%10;
       num /= 10;
   }
      return num;
}
}

You should be adding the result of modulo operation to sum . And you should return sum .

while ( num != 0){
    sum += num % 10;
    num /= 10;
 }
return sum;

You don't need these many loops, you can improve it by caching the previous outputs and reusing it (Dynamic programming tabulation) . Considering you don't have values greater than 100 following code can work for you

public static int sumDigits(int num) {
    int[] cache = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1 };
    int sum = num + cache[num % 10] + cache[num / 10];
    return sum;
}

basically, I've cached outputs for first 10 inputs.

FYI, you can make scale the program for larger inputs by storing the previous outputs in HashMap

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