-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
3b47d31
commit f93c730
Showing
1 changed file
with
77 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} |