京东笔试第1、第2道题
第一题:括号匹配问题,用递归
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
StringBuilder sb = new StringBuilder(sc.nextLine());
System.out.println(getCount(sb));
}
}
private static int getCount(StringBuilder sb) {
// TODO 自动生成的方法存根
if(sb.length()==0)
return 1;
if(sb.charAt(0)=='(')
sb.deleteCharAt(0);
else
return 0;
int count = 0;
int num = sb.length();
for(int i=0;i<num;i++){
if(sb.charAt(i)==')'){
sb.deleteCharAt(i);
count+=getCount(sb);
sb.insert(i, ')');
}
}
sb.insert(0, '(');
return count;
}
}
第2题:求幂
import java.util.Scanner;
public class CopyOfMain {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
int n = sc.nextInt();
int[] a = new int[n+1];
int num = 0;
a[1]=1;
//求约数
for(int i=2;i<n+1;i++){
num = i;
for(int j=1;j<=(int)Math.sqrt(num);j++){
if(num%j==0)
a[i]++;
}
a[i]*=2;
if(num-(int)Math.pow((int)Math.sqrt(num), 2)==0){
a[i]--;
}
}
for(int i=1;i<n+1;i++){
num=a[i]-2;
if(num==0)
a[i]=0;
else
a[i] = (num+1)*num/2;
}
num = 0;
for(int i=1;i<n+1;i++){
num+=a[i];
}
System.out.println(2*n*n-n+(n-1)*num);
}
}
}