2

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.

4

1 回答 1

3

我认为这样做的目的是这样做,n = 5368因此您需要一个循环来提取每个单独的数字并将其与当前的最小值/最大值进行比较

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);
于 2014-11-04T16:26:10.493 回答