2020-08-23爱奇艺笔试回忆
1、n的阶乘问题
正整数n的阶乘(n!)中末尾有多少个0?
下面展示一些 内联代码片
。
import java.util.Scanner;
public class T1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
if(n>0) {
if(n==1) {
System.out.println(0);
}else {
int count2=0;
int count5=0;
for(int j=2;j<=n;j++) {
int i=j;
while(i%2==0) {
i/=2;
count2++;
}
while(i%5==0) {
i/=5;
count5++;
}
}
System.out.println(Math.min(count2, count5));
}
}else {
System.out.println(0);
}
}
}
2、判断路径是否相交
给定一个字符串path,其中path[i]的 值可以是’N’‘S’‘W’‘E’,分别代表向北、南、西、动运动,机器人从(0,0)开始运动,按照path走,如果有重复路径则返回true,否则为false
import java.util.HashSet;
import java.util.Scanner;
public class T2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String path=sc.next();
int x=0,y=0;
int flag=0;
if(path.length()>0) {
HashSet<String> set=new HashSet<>();
set.add(x+","+y);
for(char c:path.toCharArray()){
switch(c) {
case 'N':
y++;
break;
case 'S':
y--;
break;
case 'E':
x++;
break;
case 'W':
x--;
break;
}
if(set.contains(x+","+y)) {
flag=1;
System.out.println("True");
break;
}
else
set.add(x+","+y);
}
if(flag==0)
System.out.println("False");
}else {
System.out.println("True");
}
}
}
3、判断字符串是否有效(括号匹配问题)
给定一个字符串’(’’)’’[’’]’’{’’}’,判断是否匹配
import java.util.Scanner;
import java.util.Stack;
public class T3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String s=sc.next();
//StringUtils.inBlank();
if(s!=null && s.length()>0) {
if("".equals(s)) {
System.out.println("True");}
if(s==" ") {
System.out.println("True");
}else {
Stack<Character> stack=new Stack();
char chars[]=s.toCharArray();
for(char c:chars) {
if(c=='(' || c=='{' || c=='[') {
stack.add(c);
}else {
if(stack.isEmpty()) {
System.out.println("False");
break;
}
if(c==')'&& stack.pop()!='(') {
System.out.println("False");
break;
}
if(c=='}'&& stack.pop()!='{') {
System.out.println("False");
break;
}
if(c==']'&& stack.pop()!='[') {
System.out.println("False");
break;
}
}
}
if(stack.isEmpty()) {
System.out.println("True");
}else {
System.out.println("False");
}
}
}else {
System.out.println("False");
}
}
}