Created
August 1, 2017 23:38
-
-
Save JiaruiTracy/b64c44d5c4199494aa759faf8b0c71e9 to your computer and use it in GitHub Desktop.
[Leetcode445 Stack Solution]Add two numbers, 4 lines
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
/* | |
* This code is to describe how to use stack implement adding two numbers. | |
* The key is the while-loop in the addTwoNum() method. | |
*/ | |
import java.util.*; | |
public class StackNumberApp { | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
Stack<Integer> s1 = new Stack<>(); | |
Stack<Integer> s2 = new Stack<>(); | |
pushNum(22, s1); | |
pushNum(99, s2); | |
Stack<Integer> s3 = new Stack<>(); | |
addTwoNum(s1, s2, s3); | |
System.out.println(s3.toString()); | |
} | |
private static void addTwoNum(Stack<Integer> s1, Stack<Integer> s2, Stack<Integer> s3) { | |
// TODO Auto-generated method stub | |
int sum = 0; | |
int carry = 0; | |
while (!s1.isEmpty() || !s2.isEmpty()||carry!=0) { | |
sum = (s1.isEmpty() ? 0 : s1.pop()) + (s2.isEmpty() ? 0 : s2.pop()) + carry; | |
s3.push(sum % 10); | |
carry = sum / 10; | |
} | |
} | |
public static void pushNum(int num, Stack<Integer> s) { | |
Stack<Integer> st = new Stack<>(); | |
while (num > 0) { | |
int t = num % 10; | |
st.push(t); | |
num = num / 10; | |
} | |
while (!st.isEmpty()) { | |
s.push(st.pop()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment