Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot push 0 to stack in java

I am newbie in Java. I have the problem. This is my code

Stack<String> st = new Stack<String>();
int num=9;
while(num > 0){
    st.push(Integer.toString(num%2));
    num/=2;
}
int d=0;
if(!st.isEmpty()){
    d++;
    st.pop();
 }
System.out.println(d);

the result is 1.
But correct is 4.
I don’t know how to fix it. Sorry if my English is not good. Thankyou

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your problem is from line 8! When you define if, however you have to write while loop, NOT if statement

Another point is that your stack should be integer and its not essential to define stack with string

So try it:

Stack<Integer> st = new Stack<>();
int num = 9, d = 0;
while(num > 0){
    st.push(num%2);
    num /= 2;
}

while(!st.isEmpty()){
    d++;
    st.pop();
 }
System.out.println(d);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading