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
>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);