Integers have the maximum limit, and if integers exceed the maximum number of digits, such as 4398912120931092319+49832232849329019019210921029, the integer variable cannot save the numbers. The solution is to save the numbers using strings, Then use the stack to do bitwise addition.
1. Java implementation, the first use of linked list LinkedList structure stack data structure.
import java.util.LinkedList;
public class IntStack {
private LinkedList<Integer> storage = new LinkedList<Integer> ();
/** 入栈 */
public void push(int v) {
storage.addFirst(v);
}
/** 出栈,但不删除 */
public int peek() {
return storage.getFirst();
}
/** 出栈 */
public int pop() {
return storage.removeFirst();
}
/** 栈是否为空 */
public boolean empty() {
return storage.isEmpty();
}
/** 打印栈元素 */
public String toString() {
return storage.toString();
}
}
2. Use stack addition operation.
2.1 Stack oper1 and Stack oper2 save two addends respectively, and stack result saves results;
The 2.2 method Pushnum (String soper1, String soper2) stores two numeric strings in two stacks respectively;
2.3 Method Add () for addition operation, the specific algorithm is:
[1] Integer variable addition save a 10-bit value, can only take a value of 0 or 1, two 9 add to 18;
[2] The loop takes the data from the two stacks, saves the single-digit value of the added result to the stack results, and the 10-bit value is stored in the integer variable addition;
[3] Integer variable addition initial value of 0, each time to participate in the next round of operations;
[4] When a addends stack (stack oper1 or stack oper2) is empty, the data of another stack is copied directly to the stack result;