Write a method named digitRange that accepts an integer as a parameter and retur
ID: 3624726 • Letter: W
Question
Write a method named digitRange that accepts an integer as a parameter and returns the range of values of its digits. The range is defined as 1 more than the difference between the largest and smallest digit value. For example, the call of digitRange(68437) would return 6 because the largest digit value is 8 and the smallest is 3, so 8 - 3 + 1 = 6. If the number contains only one digit, return 1. You should solve this problem without using a String.Explanation / Answer
Here is a solution:) import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class DigitRange { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { System.out.println("Write a number"); BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); Integer i = Integer.valueOf(r.readLine().trim()); System.out.println("The range is: " + getRange(i)); } private static int getRange(int i ) { int range = 1; int min =Integer.MAX_VALUE; int max = Integer.MIN_VALUE; if (i > 9) { while(i > 0) { int tmp = i%10; min = Math.min(tmp, min); max = Math.max(tmp, max); i /=10; } range = max -min + 1; } return range; } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.