题目:
给定两个非负整数(不含前导 0) A,B,请你计算 A/B 的商和余数
输入:
10000
9
输出:
1111
1
自己写一个?
public class 高精度除法 {
public static ArrayList<Integer> A = new ArrayList<>(), res = new ArrayList<>();
public static int B;
public static void main(String[] args) {
这里A是超长数,B是int范围内的数
Scanner in = new Scanner(System.in);
String a = in.next(); B = in.nextInt();
for (int i = a.length()-1; i>=0; i--) A.add(a.charAt(i) - '0');
//r是余数,res存储的是商
int r = divide();
for (int i = res.size()-1; i>=0; i--) System.out.print(res.get(i));
System.out.println("\n" + r);
}
//除法,这里和加/减/乘不同,计算除法要从最高位开始,不要弄混了,r是每次%B后的余数
public static int divide() {
int r = 0;
for (int i = A.size()-1; i>=0; i--) {
r = r * 10 + A.get(i);
res.add(r / B);
r %= B;
}
//因为我们从最高位开始计算除法,为了契合加/减/乘的输入输出,我们reverse一下元素即可
Collections.reverse(res);
while (res.size() > 1 && res.get(res.size()-1) == 0) res.remove(res.size()-1); //防止10000*9=01111的情况
return r;
}
}
用java自带的BigInteger函数:(注意!BigInteger这么写得不到余数,只能得到商,%一下就好)
public class Demo{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
BigInteger a = new BigInteger(in.next()), b = new BigInteger(in.next());
System.out.println(a.divide(b));
}
}
声明:算法思路来源为y总,详细请见https://www.acwing.com/
本文仅用作学习记录和交流