PAT-乙级-Java-1010/1011

105 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第30天,点击查看活动详情

-  1010 一元多项式求导 (25 分)

设计函数求一元多项式的导数。(注:x​n​​(n为整数)的一阶导数为nx​n−1​​。)

输入格式:

以指数递降方式输入多项式非零项系数和指数(绝对值均为不超过 1000 的整数)。数字间以空格分隔。

输出格式:

以与输入相同的格式输出导数多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。注意“零多项式”的指数和系数都是 0,但是表示为 0 0

输入样例:

3 4 -5 2 6 1 -2 0

输出样例:

12 3 -10 1 6 0

Java代码实现:

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String input = sc.nextLine();
		String[] split = input.split("\s+");
		StringBuffer result = new StringBuffer();
		for(int i = 0;i<split.length;i+=2){

			//系数非0指数为0
			if(Integer.parseInt(split[i+1]) == 0 && Integer.parseInt(split[i]) != 0 ){
				continue;
			}

			//系数为0
			if(Integer.parseInt(split[i]) == 0){
				result.append(0+" ");
				result.append(0+" ");
				continue;
			}

			//普通情况
			result.append(Integer.parseInt(split[i])*Integer.parseInt(split[i+1])+" "+(Integer.parseInt(split[i+1])-1)+" ");
		}
		if(result.length() == 0){//空串时输出0 0
			System.out.println("0 0");
		}else{
			System.out.println(result.substring(0, result.length()-1));
		}
	}
}

-  1011 A+B 和 C (15 分)

给定区间 [−2​^31​​,2​^31] 内的 3 个整数 A、B 和 C,请判断 A+B 是否大于 C。

输入格式:

输入第 1 行给出正整数 T (≤10),是测试用例的个数。随后给出 T 组测试用例,每组占一行,顺序给出 A、B 和 C。整数间以空格分隔。

输出格式:

对每组测试用例,在一行中输出 Case #X: true 如果 A+B>C,否则输出 Case #X: false,其中 X 是测试用例的编号(从 1 开始)。

输入样例:

4
1 2 3
2 3 4
2147483647 0 2147483646
0 -2147483648 -2147483647

输出样例:

Case #1: false
Case #2: true
Case #3: true
Case #4: false

Java代码实现:

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		int num = Integer.parseInt(sc.nextLine());
		boolean [] result = new boolean[num];
		for(int i = 1;i<num+1;i++){
			String input = sc.nextLine();
			//这道题需要注意的是题目中说了给定的区间是在-2^31~2^31,超出int范围,所以需要使用long型
			if(Long.parseLong(input.split("\s+")[0])+Long.parseLong(input.split("\s+")[1])>Long.parseLong(input.split("\s+")[2])){
				result[i-1] = true;
			}else{
				result[i-1] = false;
			}
			
		}
		for(int i = 1;i<num+1;i++){
			System.out.println("Case #"+i+": "+result[i-1]);
		}
	}
}

​ ​