华为OD笔试202010OD笔试华为OD第三题入栈操作
华为OD笔试202010OD笔试华为OD第三题入栈操作
输入 5 10 20 50 85 1 输出 1 170 输入 6 7 8 13 9 输出 9 13 8 7 6
解释
输入入栈 6 1 2 3 5 按顺序入栈 6 1 2 3 = 2 + 1 然后把 2 1 出栈,再把2*3=6入栈,此时 6=6 把6 6 出栈,再把2*6=12入栈, 5 输出: 5 12
import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int len = 0; String[] split = sc.nextLine().split(" "); int[] nums = new int[split.length]; for (int i = 0; i < split.length; i++) { int num = Integer.parseInt(split[i]); nums[len] = num; len = pushStack(nums, len); } for (int i = len - 1; i >= 0; i--) { System.out.print(nums[i] + " "); } } private static int pushStack(int[] nums, int len) { int tmpNum = nums[len]; int tmpLen = len - 1; while (tmpNum > 0 && tmpLen >= 0) { tmpNum = tmpNum - nums[tmpLen]; if (0 == tmpNum) { // 2*num nums[tmpLen] = 2 * nums[len]; len = tmpLen; int i = pushStack(nums, len); return i; } tmpLen--; } len++; return len; } }