455,800 Members | 1,300 Online
Need help? Post your question and get tips & solutions from a community of 455,800 IT Pros & Developers. It's quick & easy.

# how to add two numbers using stack in java

 100+ P: 107 hi guys, great to be back in this site after a long time. well, i am learning java and want to add two numbers using stack. int a= 123; int b=4567; i want each of the values to read one by one and push to the stack. so i will have one stack to store "a" value and another to store "b" value. then i want to add the top of stack values and store it in third stack and then once the operation is over, i need to print out the result from the third stack. please enlighten me! Apr 13 '13 #1
4 Replies

 10K+ P: 13,264 What have you tried? Apr 13 '13 #2

 100+ P: 107 Ok, the following code is missing only the remainder. I want to know how to add a remainder of previous operation to new operation. suppose below 7+6=13, i've pushed the 3 to stack and now i want the 1 to be added to (6+2)+1=9 Expand|Select|Wrap|Line Numbers package practical; import java.util.*;     public class StackAddAB {     public static void main(String[] args){         int a = 1226;         int b = 4567;         int result = 0;           a = reverseNum(a);         b = reverseNum(b);           Stack stacka = new Stack();         Stack stackb = new Stack();         Stack stackc = new Stack();           push(stacka, a);         push(stackb, b);           while (!stacka.empty() && !stackb.empty()) {         result = addValues(stacka, stackb);           push(stackc, result);         }           System.out.println("Stack A: " + stacka);         System.out.println("Stack B: " + stackb);         System.out.println("Stack C: " + stackc);       }     static void push(Stack st, int v){           while (v > 0){             st.push(v);                         v = v / 10;             }         }     static void pop(Stack st) {         st.pop();         }     static Integer addValues(Stack sta, Stack stb){         int res=0, val = 0, rem=0, x, y;           //while (!sta.empty() && !stb.empty()) {         x = sta.pop();         y = stb.pop();           res = x+y+rem;           val = res%10;         if(res>9){             rem = 1;         }         else{             rem = 0;         }           System.out.println("Value: "+val+" Remainder: "+rem);           return val;             }     static Integer reverseNum(int num){         int revNum=0;         while (num != 0) {             revNum = revNum * 10 + num % 10;             num = num / 10;            }         return revNum;     } }   Apr 13 '13 #3

 10K+ P: 13,264 Are you allowed to use java.util.Stack or are you supposed to write your own stack implementation? Apr 13 '13 #4

 100+ P: 107 its not a task assigned but i am learning it just to see how i can perform stack operations Apr 13 '13 #5