题目:794. 高精度除法 - AcWing题库
思路/想法:
首先,写代码之前自己模拟一遍,会发现和前面加减乘法在计算上顺序是不同的,除法需要顺序遍历。
运行过程中存在很多种情况,细节都在代码里了。
代码实现:
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
int b = sc.nextInt();
int[] arr = new int[s.length()];
for (int i = 0, j = 0; i < arr.length; i++){
arr[j++] = s.charAt(i) - '0';
}
List<Integer> ans = divide(arr, b);
for (int i = 0; i < ans.size() - 1; i++) {
System.out.print(ans.get(i));
}
System.out.println();
System.out.print(ans.get(ans.size() - 1));
}
public static List<Integer> divide(int[] arr, int b) {
List<Integer> ans = new ArrayList<>();
// 模拟计算
int t = 0;
for (int i = 0; i < arr.length; i++) {
t += arr[i];
if (t / b >= 0) { // ">= 0"既要考虑能整除的也要考虑中间不能整除的,但同时0应该补上,不然就少了一位,这可能造成前几位0都加到结果集了,后面会循环判断去除过多的 0
ans.add(t / b);
} else {
t *= 10; // 如果不够整除的就再退一位
continue;
}
t = t % b * 10; // 余数需要✖10
}
ans.add(t / 10); // 最后一位是余数
int i = 0;
while (ans.size() > 2 && ans.get(i) == 0) ans.remove(ans.get(i)); // 去除多余的 0
return ans;
}
}