2020腾讯4月26日笔试题第一四五题求助输入输出的问题
第一题,这一道题的输入输出问题在while(size-->=0),求解,为什么加上等号就能AC?假如我获取的是7,那么这个while循环执行了8次啊?为什么?我原来没写等号,出现数组越界
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int count=in.nextInt(); while (in.hasNext()) {// 注意,如果输入是多个测试用例,请通过while循环处理多个测试用例 int size=in.nextInt(); LinkedList<Integer> queue=new LinkedList<>(); while(size-->=0) { String str=in.nextLine(); if(str.equals("TOP")) { if(queue.size()==0) { System.out.println(-1); }else { System.out.println(queue.peek()); } }else if(str.equals("POP")) { if(queue.size()==0) { System.out.println(-1); }else { queue.poll(); } }else if(str.equals("SIZE")) { System.out.println(queue.size()); }else if(str.equals("CLEAR")) { queue.clear(); } else if(str.startsWith("PUSH")) { String[] s=str.split(" "); int temp=Integer.parseInt(s[1]); queue.add(temp); } } } } }第四题,虽然他让我用两个栈实现队列,但是内部用什么实现他也不知道啊,他怎么检测的,在leetcode上我也做过相应的题,这道题我就偷懒一下,直接复制第一题改了改,但是超时,只通过75%
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) {// 注意,如果输入是多个测试用例,请通过while循环处理多个测试用例 int size=in.nextInt(); LinkedList<Integer> queue=new LinkedList<>(); while(size-->0) { String str=in.nextLine(); if(str.equals("peek")) { if(queue.size()==0) { System.out.println(-1); }else { System.out.println(queue.peek()); } }else if(str.equals("poll")) { if(queue.size()!=0) { queue.poll(); } }else { String[] s=str.split(" "); int temp=Integer.parseInt(s[1]); queue.add(temp); } } } } }第五题 就是树的题,我用一个函数,输入编号,计算深度,还是数组越界,他提示我Long flag=Long.parseLong(strings[0]);这一句,string="",不应该为空啊
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) {// 注意,如果输入是多个测试用例,请通过while循环处理多个测试用例 int count=in.nextInt(); while(count-->0) { String string=in.nextLine(); String[] strings=string.split(" "); Long flag=Long.parseLong(strings[0]); int depth=Integer.parseInt(strings[1]); if(depth<=0) { System.out.println(-1); } if(calDepth(flag)<=depth) { System.out.println(-1); }else { Long fatherFlag=flag/2; while(calDepth(fatherFlag)!=depth) { fatherFlag=fatherFlag/2; } System.out.println(fatherFlag); } } } } public static int calDepth(Long flag) { int count=0; while(flag>=Math.pow(2,count)) { count++; } return count; } }