摘要
高精度运算是指参与运算的数远大于标准数据类型的数,动辄成百上千位的数。所以高精度数又被称为大数。
本文主要讲解:大数加法,大数减法,大数乘法,大数除法,大数阶乘。
java的大数类做这一类题很方便,效率高代码短,但是学会高精度算法还是很有必要的。
另外注意,不是数大的题就是高精度题,要注意审题,比如裸快速幂的题,虽然数很大,但是跟高精度不沾边。
蓝桥杯基础算法和常用API集合:https://blog.youkuaiyun.com/GD_ONE/article/details/104061907
大数加法
例题:
基础练习 高精度加法
先给出大数类的写法:
import java.util.*;
import java.io.*;
import java.math.*;
public class Main{
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] agrs) throws IOException{
String s = in.readLine();
BigInteger a = new BigInteger(s);
String s1 = in.readLine();
BigInteger b = new BigInteger(s1);
a = a.add(b);
out.write(a.toString());
out.flush();
}
}
数组模拟:
因为基本数据类型存不下,所以我们只能将两个数按字符串存储,为了方便计算我们可以将每一位都转化成数字并保存在数组中。然后按位相加,模拟我们平常手算加法的步骤。
比如说 11 + 8 11+ 8 11+8, 我们要先算各位, 1 + 8 = 9 1+8 = 9 1+8=9,然后算十位, 1 + 0 = 1 1+0 = 1 1+0=1所以答案是 19 19 19。
那么如果遇到进位怎么办,比如 12 + 8 , 个 位 是 2 + 8 = 10 12+8, 个位是2+8=10 12+8,个位是2+8=10,需要向十位进1,也就是算十位的时候要多加上1,对于不进位的情况,其实就是算十位的时候多加0,进几就多加几。
为了使代码更简洁我们不用一个变量专门保存进位多少,我们算出个位的和之后,让其对10取模,就得到了个位要保留多少,然后让和除以10,如果不为0,就说明需要进位。
比如:
9 % 10 = 9 , 9 / 10 = 0 9\%10 = 9, 9 / 10 = 0 9%10=9,9/10=0也就是说,个位保留9, 不进位。
10 % 10 = 0 , 10 / 10 = 1 10\%10 = 0, 10 / 10 = 1 10%10=0,10/10=1也就是说,个位保留0, 进1。
import java.util.*;
import java.io.*;
import java.math.*;
public class Main{
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] agrs) throws IOException{
String s = in.readLine();
String s1 = in.readLine();
int lena = s.length();
int lenb = s1.length();
// 也可以用静态数组。
ArrayList<Integer> a = new ArrayList<>();
ArrayList<Integer> b = new ArrayList<>();
for(int i = lena - 1; i >= 0; i--) a.add(s.charAt(i) - '0'); // 先对数字进行处理,保存在数组中。
for(int i = lenb - 1; i >= 0; i--) b.add(s1.charAt(i) - '0');// 因为需要从个位开始加,所以倒序存储。
ArrayList<Integer> c = new ArrayList<>();
// c = a + b
int r = 0;
for(int i = 0; i < lena || i < lenb; i++){
if(i < lena) r += a.get(i);
if(i < lenb) r += b.get(i);
c.add(r%10);
r /= 10;
}
// 最后判断一下最高位是否进位。
if(r != 0) c.add(r);
for(int i = c.size

最低0.47元/天 解锁文章
4万+

被折叠的 条评论
为什么被折叠?



