Untitled
unknown
plain_text
2 years ago
2.0 kB
7
Indexable
import unit4.collectionsLib.*;
public class Ex5 {
public static int countDigs(int num) {
int count = 1;
while (num > 9) {
num /= 10;
count++;
}
return count;
}
public static int revNum(int num) {
int newNum = 0;
while (num != 0) {
int digit = num % 10;
newNum = newNum * 10 + digit;
num /= 10;
}
return newNum;
}
public static boolean numDigsInStack(Stack<Integer> s, int num) {
Stack<Integer> temp = new Stack<Integer>();
int numCopy = num;
int reverseNum = revNum(num);
int reverseNumCopy = reverseNum;
int current;
while (!s.isEmpty()) {
current = s.pop();
temp.push(current);
boolean flag;
if (current == num % 10) {
flag = true;
num /= 10;
} else
flag = false;
if (!flag)
num = numCopy;
if (num == 0) {
while (!temp.isEmpty()) {
s.push(temp.pop());
}
return true;
}
}
while (!temp.isEmpty()) {
s.push(temp.pop());
}
while (!s.isEmpty()) {
current = s.pop();
temp.push(current);
boolean flag;
if (current == reverseNum % 10) {
flag = true;
reverseNum /= 10;
} else
flag = false;
if (!flag)
reverseNum = reverseNumCopy;
if (reverseNum == 0) {
while (!temp.isEmpty()) {
s.push(temp.pop());
}
return true;
}
}
while (!temp.isEmpty()) {
s.push(temp.pop());
}
return false;
}
public static void main(String[] args) {
Stack<Integer> stack1 = new Stack<>();
stack1.push(3);
stack1.push(1);
stack1.push(4);
stack1.push(6);
stack1.push(4);
stack1.push(1);
stack1.push(3);
stack1.push(2);
stack1.push(1);
System.out.println(stack1);
System.out.println(numDigsInStack(stack1, 6413));
System.out.println(numDigsInStack(stack1, 314));
System.out.println(numDigsInStack(stack1, 41));
System.out.println(numDigsInStack(stack1, 415));
System.out.println(numDigsInStack(stack1, 115));
}
}
Editor is loading...
Leave a Comment