Skip to content

Instantly share code, notes, and snippets.

@jerrylususu
Created March 11, 2018 17:05
Show Gist options
  • Save jerrylususu/23c11c94ed85655500db41a4212eff2f to your computer and use it in GitHub Desktop.
Save jerrylususu/23c11c94ed85655500db41a4212eff2f to your computer and use it in GitHub Desktop.
BIG A+B
import java.util.Scanner;
public class aplusb {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String a = "";
String b = "";
while(a.isEmpty()||b.isEmpty()) {
if(a.isEmpty()) {
a=input.nextLine();
}
if(b.isEmpty()) {
b=input.nextLine();
}
}
input.close();
System.out.println(add(a,b));
}
public static String add(String a, String b) {
int sizeA = a.toCharArray().length;
int sizeB = b.toCharArray().length;
int sizeMAX = (sizeA>sizeB)?sizeA+1:sizeB+1;
int[] addedr = new int[sizeMAX];
int addstore = 0;
String small = (sizeA>sizeB)?b:a;
String big = (sizeA>sizeB)?a:b;
String sr = reverse(small);
String br = reverse(big);
char[] src = sr.toCharArray();
char[] brc = br.toCharArray();
for(int i=0;i<sizeMAX;i++) {
int sd = 0,bd = 0;
try {
sd = (i<src.length)?Integer.parseInt(String.valueOf(src[i])):0;
bd = (i<brc.length)?Integer.parseInt(String.valueOf(brc[i])):0;
} catch (Exception e) {
System.out.println(a);
System.out.println(b);
}
int curadd = sd+bd+addstore;
addstore=0;
if(curadd>=10) {
addstore = 1;
}
addedr[i]=curadd%10;
}
String r = "";
for(int i=0;i<addedr.length;i++) {
if(i==addedr.length-1&&addedr[i]==0) {
;
}else {
r+=addedr[i];
}
}
return reverse(r);
}
public static String reverse(String a) {
String r = "";
char[] ac = a.toCharArray();
for(int i = ac.length-1;i>=0;i--) {
r+=ac[i];
}
return r;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment