218k views
2 votes
Write a program that will take an integer and add up each of the number’s digits, count the number of digits in the number, and then average the digits. You must use a while loop and % to access each of the individual digits. Use / to reduce the number so that you can average all of the digits.

Example: num = 123 can be taken apart with tempNum = 123 % 10 (which will pull off the 3), then tempNum = tempNum / 10 (will result in 12). Do this in a loop while the number is > 0.

Sample Data :
234
10000
111
9005
84645
8547
123456789


 Be sure to include print statements that will format the output as below.

Sample Output :
234 has a digit average of 3.0

10000 has a digit average of 0.2

111 has a digit average of 1.0

9005 has a digit average of 3.5

84645 has a digit average of 5.4

8547 has a digit average of 6.0

123456789 has a digit average of 5.0

Write a program that will take an integer and add up each of the number’s digits, count-example-1

2 Answers

5 votes
For count digits, you could just convert it to a String and check the length
Sum digits, convert to string then seperate each character with charAt then convert it to numbers in the return statement.
Average digits you can convert it to a String and then convert them back after taking them apart.
User Souradeep Nanda
by
6.5k points
3 votes
Here is my solution:

import java.lang.System.*;

public class DigiMath {

private static int countDigits(int number)
{
int sum = 0;
while(number > 0)
{
sum ++;
number /= 10;
} return sum;
}

private static int sumDigits(int number)
{
int sum = 0;
while(number > 0) {
sum += number % 10;
number /= 10;
}
return sum;
}

public static double averageDigits( int number )
{
int count = countDigits(number);
if (count > 0) {
return (double)sumDigits(number) / (double)count;
} else {
return 0;
}
}

public static void PrintDigitAverage(int number)
{
System.out.printf("%d has a digit average of %1.1f\\", number, averageDigits(number));
}

public static void main(String[] args)
{
// Method tests (run with java -ea)
assert countDigits(12345) == 5 : "countDigits returns wrong count";
assert sumDigits(12345) == 15 : "sumDigits returns wrong sum";
assert averageDigits(12345) == 3.0: "averageDigits returns wrong average";

PrintDigitAverage(234);
PrintDigitAverage(10000);
PrintDigitAverage(111);
PrintDigitAverage(9005);
PrintDigitAverage(84645);
PrintDigitAverage(8547);
PrintDigitAverage(123456789);
}
}


User Halfbit
by
7.4k points