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.

allejo
  • 2,076
  • 4
  • 25
  • 40
Oktavix
  • 151
  • 1
  • 2
  • 9
  • possible duplicate of [Java: Max/min value in an array?](http://stackoverflow.com/questions/1484347/java-max-min-value-in-an-array) – jruizaranguren Nov 04 '14 at 16:03
  • 1
    One solution: use `String.valueOf(int)` to convert your number to an `String`, get its `char[]`, sort it, get first and last index. To extract value of each character, just use `c - '0'`. That's it! – Amir Pashazadeh Nov 04 '14 at 16:07

1 Answers1

3

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);
Alex K.
  • 171,639
  • 30
  • 264
  • 288