SHOW:
|
|
- or go back to the newest paste.
1 | // Author : Saurav Kalsoor | |
2 | - | // Sort By Digit Sum - JAVA |
2 | + | // Sort By Reversing Digits - JAVA |
3 | ||
4 | import java.util.*; | |
5 | ||
6 | public class Test { | |
7 | ||
8 | static Scanner sc = new Scanner(System.in); | |
9 | public static void main(String[] args) { | |
10 | int n = sc.nextInt(); | |
11 | ArrayList<Integer> arr = new ArrayList<>(); | |
12 | ||
13 | for(int i=0; i < n; i++) { | |
14 | int input = sc.nextInt(); | |
15 | arr.add(input); | |
16 | } | |
17 | ||
18 | ArrayList<Integer> result = sortByDigits(arr); | |
19 | ||
20 | for(int i=0; i < n; i++) | |
21 | System.out.print(result.get(i) + " "); | |
22 | ||
23 | System.out.println(); | |
24 | } | |
25 | ||
26 | public static ArrayList<Integer> sortByDigits(ArrayList<Integer> arr){ | |
27 | - | Collections.sort(arr, new SortBySumOfDigits()); |
27 | + | Collections.sort(arr, new SortByReversingDigits()); |
28 | return arr; | |
29 | } | |
30 | } | |
31 | ||
32 | - | class SortBySumOfDigits implements Comparator<Integer> { |
32 | + | class SortByReversingDigits implements Comparator<Integer> { |
33 | ||
34 | public int compare(Integer a, Integer b){ | |
35 | ||
36 | - | int sumA = getSum(a), sumB = getSum(b); |
36 | + | int revA = reverseDigits(a), revB = reverseDigits(b); |
37 | - | if(sumA == sumB){ |
37 | + | if(revA == revB){ |
38 | return a - b; | |
39 | } | |
40 | else{ | |
41 | - | return sumA - sumB; |
41 | + | return revA - revB; |
42 | } | |
43 | } | |
44 | ||
45 | - | public int getSum(int n){ |
45 | + | public int reverseDigits(int n){ |
46 | - | int sum = 0; |
46 | + | int rev = 0; |
47 | while(n > 0){ | |
48 | - | sum = sum + n%10; |
48 | + | rev = rev * 10; |
49 | rev = rev + n%10; | |
50 | n = n/10; | |
51 | - | return sum; |
51 | + | |
52 | return rev; | |
53 | } | |
54 | } | |
55 | ||
56 |