How to sort Integer digits in ascending order without Strings or Arrays?

前端 未结 8 707
傲寒
傲寒 2020-12-06 06:32

I\'m trying to sort the digits of an integer of any length in ascending order without using Strings, arrays or recursion.

Example:

Input: 451467
Outp         


        
相关标签:
8条回答
  • 2020-12-06 07:19
    class SortDigits {
        public static void main(String[] args) {
            int inp=57437821;
            int len=Integer.toString(inp).length();
            int[] arr=new int[len];
            for(int i=0;i<len;i++)
            {
                arr[i]=inp%10;
                inp=inp/10;
            }
            Arrays.sort(arr);
            int num=0;
            for(int i=0;i<len;i++)
            {
                num=(num*10)+arr[i];
            }
            System.out.println(num);
        }    
    }
    
    0 讨论(0)
  • 2020-12-06 07:29

    I assume you're allowed to use hashing.

    public static void sortDigits(int x) {
        Map<Integer, Integer> digitCounts = new HashMap<>();
    
        while (x > 0) {
            int digit = x % 10;
            Integer currentCount = digitCounts.get(digit);
            if (currentCount == null) {
                currentCount = 0;
            }
            digitCounts.put(x % 10, currentCount + 1);
            x = x / 10;
        }
    
        for (int i = 0; i < 10; i++) {
            Integer count = digitCounts.get(i);
            if (count == null) {
                continue;
            }
            for (int j = 0; j < digitCounts.get(i); j++) {
                System.out.print(i);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题