java - control structure, repetition exercise: How to get the sum of the digits of a number? -
guys can please me answer exercise using loop without using string methods.
write program prompts user input integer , outputs both individual digits of number , sum of digits. example, program should output individual digits of 3456 3 4 5 6 , sum 18,and output individual digits of -2345 2 3 4 5 , sum 14.
this code:
package mypackage; import java.util.*; public class integer { public static void main(string args[]) { scanner console = new scanner (system.in); int input; int sum = 0; int num1 = 0; int counter = 1; string num = ""; system.out.print("enter number: "); input = console.nextint(); if (input == (-input)) { input = input * (-1); num = string.valueof(input); num1 = num.length(); system.out.print("the digits of " + input + " are: "); (int = 0; < num1; i++ ) { string var = num.substring(i,counter); int var1 = character.getnumericvalue(var.charat(0)); system.out.print(var + " "); sum = sum + var1; counter++; } system.out.println(); system.out.println("the sum is: " + sum); } else { num = string.valueof(input); num1 = num.length(); system.out.print("the digits of " + input + " are: "); (int = 0; < num1; i++ ) { string var = num.substring(i,counter); int var1 = character.getnumericvalue(var.charat(0)); system.out.print(var + " "); sum = sum + var1; counter++; } system.err.println(); system.out.println("the sum is: " + sum); } } }
iterating digits from right left easy enough - keep dividing 10 , keeping remainder. since need print them left right, there don't seem constraint on memory usage, keep them in list, , print backwards:
int num = ...; // inputed user list<integer> digits = new linkedlist<>(); int sum = 0; // extract digits , sum while (num != 0) { int digit = num % 10; digits.add (digit); sum += digit; num /= 10; } // print backwards: system.out.print ("the digits are: "); (int = digits.size() - 1; >= 0; --i) { system.out.print (digits.get(i) + " "); } system.out.println(); system.out.println("their sum is: " + sum);
Comments
Post a Comment