简体   繁体   中英

How do i find the highest digit in a multi-digit number?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM