1
+ package com .codefortomorrow .intermediate .chapter11 .solutions ;
2
+
3
+ import java .util .Scanner ;
4
+
5
+ /*
6
+ Write a method that computes the sum of the digits
7
+ in an integer. Use the following method header:
8
+
9
+ public static int sumDigits(long n)
10
+
11
+ For example, sumDigits(234) returns 9 (because 2 + 3 + 4).
12
+
13
+ Hint: Use the % operator to extract digits,
14
+ and the / operator to remove the extracted digit.
15
+ For instance, to extract 4 from 234, use 234 % 10 (= 4).
16
+ To remove 4 from 234, use 234 / 10 (= 23).
17
+
18
+ Use a loop to repeatedly extract and remove the digit
19
+ until all the digits are extracted.
20
+
21
+ Write a test program that prompts the user to enter an integer and
22
+ displays the sum of all its digits.
23
+
24
+ Bonus points for writing a JavaDoc comment for the sumDigits method.
25
+
26
+ Adapted from Exercise 6.2, Introduction to Java Programming (Comprehensive),
27
+ 10th ed. by Y. Daniel Liang
28
+ */
29
+
30
+ public class SumDigits {
31
+ public static void main (String [] args ) {
32
+ // prompt user for integer
33
+ Scanner input = new Scanner (System .in );
34
+ System .out .print ("Enter an integer: " );
35
+ long n = input .nextLong ();
36
+ input .close ();
37
+
38
+ // print the sum of the digits in that integer
39
+ System .out .println ("Sum of digits in " + n + ": " + sumDigits (n ));
40
+ }
41
+
42
+ /**
43
+ * Return the sum of all of the digits
44
+ * in the given number
45
+ * @param n a number to sum the digits of
46
+ * @return the sum of all of the digits
47
+ * in the given number
48
+ */
49
+ public static int sumDigits (long n ) {
50
+ int sum = 0 ;
51
+ while (n > 0 ) {
52
+ // extract last digit and add it to sum
53
+ sum += n % 10 ;
54
+
55
+ // remove the last digit
56
+ n /= 10 ;
57
+ }
58
+ return sum ;
59
+ }
60
+ }
0 commit comments