Skip to content

Commit

Permalink
Create Minimum sum
Browse files Browse the repository at this point in the history
  • Loading branch information
dishathakurata authored Dec 11, 2024
1 parent 3b47d31 commit f93c730
Showing 1 changed file with 77 additions and 0 deletions.
77 changes: 77 additions & 0 deletions Minimum sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
//Minimum sum

import java.io.*;
import java.lang.*;
import java.util.*;

class GFG {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());

while (t-- > 0) {
String arr[] = br.readLine().split(" ");
int a[] = new int[arr.length];

for(int i = 0; i < arr.length; i++) {
a[i] = Integer.parseInt(arr[i]);
}

Solution obj = new Solution();
int f = 0;
String A = obj.minSum(a);
System.out.println(A);
System.out.println("~");
}
}
}

class Solution {
String minSum(int[] arr) {
Arrays.sort(arr);
StringBuilder s1 = new StringBuilder();
StringBuilder s2 = new StringBuilder();

for(int i = 0; i < arr.length; i++) {
if(i % 2 == 0) {
s1.append(arr[i]);
}
else {
s2.append(arr[i]);
}
}

return addString(s1, s2);
}

static String addString(StringBuilder s1, StringBuilder s2) {
int i = s1.length() - 1;
int j = s2.length() - 1;
int carry = 0;
StringBuilder res = new StringBuilder();

while(i >= 0 || j >= 0 || carry > 0) {
int sum = carry;

if(i >= 0) {
sum += (s1.charAt(i) - '0');
}
if(j >= 0) {
sum += (s2.charAt(j) - '0');
}

res.append(sum % 10);
carry = sum / 10;
i--;
j--;
}

while(res.length() > 0 && res.charAt(res.length() - 1) == '0') {
res.deleteCharAt(res.length() - 1);
}

res.reverse();

return res.toString();
}
}

0 comments on commit f93c730

Please sign in to comment.