Skip to content

Instantly share code, notes, and snippets.

@masious
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masious/a33dee8fa9d76f23cc9a to your computer and use it in GitHub Desktop.
Save masious/a33dee8fa9d76f23cc9a to your computer and use it in GitHub Desktop.
DS Questions - Question 3
package q3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
int a = readInt();
int b = readInt();
LinkedList all = new LinkedList();
LinkedList bll = new LinkedList();
while(a+b!=0){
all.add(new Integer(a%1000));
a /= 1000;
bll.add(new Integer(b%1000));
b /= 1000;
}
LinkedList cll = new LinkedList();
int f = Math.max(all.size(),bll.size());
boolean hasCarry = false;
for(int i=0;i<f;i++){
int result = ((Integer)all.removeFirst()).intValue() + ((Integer)bll.removeFirst()).intValue() + (hasCarry?1:0);
hasCarry = result>999;
result %= 1000;
cll.add(new Integer(result));
}
if(hasCarry)
cll.add(new Integer(1));
Iterator ci = cll.iterator();
String res = "";
while(ci.hasNext()){
Integer i = (Integer) ci.next();
res = (i.equals(new Integer(0))?"000":(i+"")) + res;
System.out.println(i+ "=>" +res);
}
System.out.println(res);
}
private static int readInt() {
int a = 0;
try {
a = new Integer(new BufferedReader(new InputStreamReader(System.in)).readLine()).intValue();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return a;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment