Advertisement
gelita

Sort digits

Feb 9th, 2020
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.47 KB | None | 0 0
  1.  
  2.   import java.io.*;
  3.   import java.util.*;
  4.  
  5.   class MyCode {
  6.    /**
  7.    * 7  Sort Digits
  8.    *
  9.    * Given an integer, sort the digits in ascending order and return the new integer.
  10.    * Ignore leading zeros.
  11.    *
  12.    * Parameters
  13.    * Input: num {Integer}
  14.    * Output: {Integer}
  15.    *
  16.    * Constraints
  17.    * Do not convert the integer into a string or other data type.
  18.    *
  19.    * Time: O(N) where N is the number of digits.
  20.    * Space: O(1)
  21.    *
  22.    * Examples
  23.    * 8970 --> 789
  24.    * 32445 --> 23445
  25.    * 10101 --> 111
  26.    */
  27.  
  28.  
  29.     public static void main (String[] args) {
  30.       //String one = "The cat and the hat.";
  31.       //String two = "As soon as possible.";
  32.       //String three = "It's a man, it's a plane, it's superman!";
  33.       int one = 8970;
  34.       int two = 32445;
  35.       int three = 10101;      
  36.       System.out.println(sortDigits(one));  
  37.     }
  38.      
  39.       public static int sortDigits(int n) {
  40.         int[] digits = new int[10];
  41.         while (n != 0) {
  42.             //tally the count of each digit in the integer
  43.             digits[n % 10]++;
  44.             // divide the input by 10 to get the next digit and repeat
  45.             n /= 10;
  46.         }
  47.         int result = 0;
  48.         //start for loop at 1 to eliminate any (leading) zeros
  49.         for (int i = 1;  i < digits.length; i++) {
  50.             for (int count = digits[i]; count > 0; count--) {
  51.                 result = result * 10 + i;
  52.             }
  53.         }
  54.         return result;
  55.       }
  56.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement