Scramble each digit of the int a and print out the biggest possible integer

后端 未结 4 529
孤独总比滥情好
孤独总比滥情好 2021-01-29 15:15

I’m stuck here. Do I just keep making new strings and turn them to int or us there a faster better way?

public void biggest(int a){
       int random;
       Stri         


        
4条回答
  •  自闭症患者
    2021-01-29 15:31

    There's no need to use conversion to String in this case, you can get the digits from the input number by getting a remainder by modulo 10, then dividing the input number by 10 and repeat it while the number > 0.

    Each digit should be stored in an array or list.

    To get the biggest number of these digits you should just sort them (standard facilities such as Arrays.sort or Collections.sort will do fine) and then "re-assemble" the biggest number from the lowest digit by multiplying it by 1, 10, 100, etc. and summing up.

    So, plain implementation could be as follows:

    public static int biggestPlain(int a) {
        List digits = new ArrayList<>();
        while (a > 0) {
            digits.add(a % 10);
            a /= 10;
        }
        Collections.sort(digits);
        int p = 1;
        int num = 0;
        for (int digit : digits) {
            num += p * digit;
            p *= 10;
        }
        return num;
    }
    

    Also, this task can be implemented using Stream API and lambda and applying the same approach:

    public static int biggestStream(int a) {
    
        AtomicInteger p = new AtomicInteger(1); // accumulate powers of 10
    
        return IntStream.iterate(a, n -> n > 0, n -> n / 10) // divide input number by 10 while it > 0
                        .map(i -> (i % 10)) // get the digit
                        .sorted() // sort (the lower digits first)
                        .map(i -> p.getAndUpdate((x) -> x * 10) * i) // same as p * digit above
                        .sum(); // get the result number
    }
    

    Update
    Iterate over digits from '9' till '0' and check if they are available in the string presentation of the input number.

    String-based solution:

    public static void biggest(int a) {
    
        String aS = String.valueOf(a);
        if (a < 10) {
            System.out.println(a);
        }
        String num = "";
        int count = 0;
        out: for (char i = '9'; i >= '0'; i--) {
            for (int j = 0; j < aS.length(); j++) {
                char digit = aS.charAt(j);
                if (digit == i) {
                    num += digit;
                    if (++count == aS.length()) {
                        break out;
                    }
                }
            }
        }
        System.out.println(num + " / " + Integer.parseInt(num));
    }
    

提交回复
热议问题