【JAVA】PAT 乙级 1017 A除以B

【JAVA】PAT 乙级 1017 A除以B


题目链接
本题要求计算 A/B,其中 A 是不超过 1000 位的正整数,B 是 1 位正整数。你需要输出商数 Q 和余数 R,使得 A=B×Q+R 成立。

输入格式:
输入在一行中依次给出 A 和 B,中间以 1 空格分隔。

输出格式:
在一行中依次输出 Q 和 R,中间以 1 空格分隔。

输入样例:
123456789050987654321 7

输出样例:
17636684150141093474 3

本题是一道模拟题,模拟算除法的过程,因为输入很大,会超过long的范围,所以不能直接除,JAVA虽然有一个BigInteger类,专门用来处理大数,但是会超时,我一开始就是用BigInteger结果超时了。

当然你也可以选择用Python来写

ip=input().split(" ")
a=int(ip[0])
b=int(ip[1])
Q=a//b
R=a%b
print("{0} {1}".format(Q,R))

要是用JAVA的话就得模拟除法的过程,可以在纸上列竖式一步步看看是怎么算的。
这里要注意的是被除数的第一位数字(假设是t从左往右数),如果t>b,商Q的第一位就是t/b,余数R等于t%b,否则的话商Q先不用管,余数R等于t。
接下来从被除数的第二位开始,一位一位处理,每一次循环的被除数tem=tem = r * 10 + t ,每次循环Q加上tem/b(这个是附加的意思,不是四则运算的加),余数每次循环都等于tem%b

JAVA代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

public class Main{
	public static void main(String[] args) throws Exception {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
		String[] ab = bf.readLine().split(" ");
		int b = sti(ab[1]);
		String q = "";//商
		String a = ab[0];//用String储存被除数
		if (a.length() == 1) {
		//被除数只有一位的情况下
			int tem = sti(a);
			out.println(tem / b + " " + tem % b);
		} else {
			int r = a.charAt(0) - '0';//余数
			char t = a.charAt(0);//首位数字
			if ((t - '0') > b) {
				//首位数字比b大
				//商q为t/b
				//余数r为t%b
				q = (t - '0') / b+"";
				r = (t - '0') % b;
			} 
			for (int i = 1; i < a.length(); i++) {
				t = a.charAt(i);
				int tem = r * 10 + t - '0';
				q += tem / b;
				r = tem % b;
			}
			out.println(q + " " + r);
		}
		out.flush();

	}

	static int sti(String a) {
		return Integer.parseInt(a);
	}
}
发布了39 篇原创文章 · 获赞 0 · 访问量 234

猜你喜欢

转载自blog.csdn.net/TAL_DARIM/article/details/105736322