Okay so I have an exercise to do I need to find the highest and the lowest digit in a number and add them together.So I have a number n which is 5368 and the code needs to find the highest (8) and the lowest (3) number and add them together (11).How do i do that?I have tried something like this:
public class Class {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n1 = 5;
int n2 = 3;
int n3 = 6;
int n4 = 8;
int max = Math.max(n2 ,n4);
int min = Math.min(n2, n4);
int sum = max + min;
System.out.println(sum);
}
}
Which kinda works but I have a 4 digit number here and with Math.max/min I can only use 2 arguments.How do I do this?Thanks in advance.
I assume the intention is to do it from n = 5368
so you will need a loop to pull of each individual digit and compare it to the current min/max
int n = 5368;
int result = 0;
if (n > 0) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
while (n > 0) {
int digit = n % 10;
max = Math.max(max, digit);
min = Math.min(min, digit);
n /= 10;
}
result = min + max;
}
System.out.println(result);