Minh Thanh
Minh Thanh

Reputation: 41

Reorder numbers in a int number to get minimum value

How can I reorder numbers in a int number to get minimum value. Ex: I input a number: $71440 and I want my output is: $1447 (this is minimum value after reordering). I think I will spits the numbers in my input number first like this , after that I will reorder them. That is good algorithm?

Upvotes: 0

Views: 382

Answers (4)

Lars
Lars

Reputation: 1750

For readability I think Diasiares answer is better. However a different approach would be something like this. It sorts a long with a "merge sort like" algorithm. To understand how it works please view the gif file from wikipedia

public static long sort(long num) {
    long res;
    if (num > 9) {
        //split num into two parts(n1, n2)
        int numberOfDigits = (int) Math.log10(num) + 1;
        long n1 = num / (long) Math.pow(10, numberOfDigits / 2);
        long n2 = num % (long) Math.pow(10, numberOfDigits / 2);

        //sort each part
        long s1 = sort(n1);
        long s2 = sort(n2);

        //merge them into one number
        res = merge(s1, s2);
    } else {
        res = num;
    }
    return res;
}

/**
 * merges two sorted long into on long e.g 149 and 345 will give 134459
 */
public static long merge(long num1, long num2) {
    return (num1 == 0 || num2 == 0)
            ? num1 + num2
            : num1 % 10 < num2 % 10
                    ? num2 % 10 + merge(num1, num2 / 10) * 10
                    : num1 % 10 + merge(num1 / 10, num2) * 10;
}

Upvotes: 0

Diasiare
Diasiare

Reputation: 755

I think this does roughly what you want it to do. Assumes that the input is positive, I'm sure you can figure out how to modify it to work with negative numbers if you need that.

public static int leastValue(int input) {
    String s = Integer.toString(input);
    char[] c = s.toCharArray();
    Arrays.sort(c);
    s = new String(c);   
    return Integer.parseInt(s);
}

The basic idea is:

  1. Turn value into a string
  2. Put each character into an array
  3. Sort the array of characters, in most character sets this will order the numbers from smallest to largest.
  4. Turn it into a string again
  5. Parse it into an int

Upvotes: 0

kyriakosSt
kyriakosSt

Reputation: 1772

What you need is essentially a sorting of the digits of the number. So yes, your proposed method will work and it seems as a reasonable practice.

Upvotes: 0

Bartosz Bilicki
Bartosz Bilicki

Reputation: 13235

Yes it is good if you

  • split by digit
  • sort digits
  • make number out of those digits

Upvotes: 2

Related Questions