Advertisement
saurav_kalsoor

Sort By Digits Sum - JAVA

Jan 24th, 2022
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.21 KB | None | 0 0
  1. // Author : Saurav Kalsoor
  2. // Sort By Digit Sum - 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());
  28.         return arr;
  29.     }
  30. }
  31.  
  32. class SortBySumOfDigits implements Comparator<Integer> {
  33.  
  34.     public int compare(Integer a, Integer b){
  35.  
  36.         int sumA = getSum(a), sumB = getSum(b);
  37.         if(sumA == sumB){
  38.             return a - b;
  39.         }
  40.         else{
  41.             return sumA - sumB;
  42.         }
  43.     }
  44.  
  45.     public int getSum(int n){
  46.         int sum = 0;
  47.         while(n > 0){
  48.             sum = sum + n%10;
  49.             n = n/10;
  50.         }
  51.         return sum;
  52.     }
  53. }
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement