Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- class MyCode {
- /**
- * 7 Sort Digits
- *
- * Given an integer, sort the digits in ascending order and return the new integer.
- * Ignore leading zeros.
- *
- * Parameters
- * Input: num {Integer}
- * Output: {Integer}
- *
- * Constraints
- * Do not convert the integer into a string or other data type.
- *
- * Time: O(N) where N is the number of digits.
- * Space: O(1)
- *
- * Examples
- * 8970 --> 789
- * 32445 --> 23445
- * 10101 --> 111
- */
- public static void main (String[] args) {
- //String one = "The cat and the hat.";
- //String two = "As soon as possible.";
- //String three = "It's a man, it's a plane, it's superman!";
- int one = 8970;
- int two = 32445;
- int three = 10101;
- System.out.println(sortDigits(one));
- }
- public static int sortDigits(int n) {
- int[] digits = new int[10];
- while (n != 0) {
- //tally the count of each digit in the integer
- digits[n % 10]++;
- // divide the input by 10 to get the next digit and repeat
- n /= 10;
- }
- int result = 0;
- //start for loop at 1 to eliminate any (leading) zeros
- for (int i = 1; i < digits.length; i++) {
- for (int count = digits[i]; count > 0; count--) {
- result = result * 10 + i;
- }
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement