本文主要是介绍66. 加一(Java):BigInteger,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
目录
- 题目描述:
- 输入:
- 输出:
- 知识点(BigInteger):
- 代码实现:
题目描述:
给定一个由 整数 组成的 非空 数组所表示的非负整数,在该数的基础上加一。
最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。
你可以假设除了整数 0 之外,这个整数不会以零开头。
输入:
digits = [4,3,2,1]
输出:
[4,3,2,2]
解释:输入数组表示数字 4321。
知识点(BigInteger):
BigInteger
是Java中的一个类,用于处理大整数的运算
。
它提供了很多方法来执行基本的数学运算,包括加法、减法、乘法、除法等。
以下是一些BigInteger的常用用法:
- 创建BigInteger对象:
BigInteger可以使用字符串表示的数字创建对象,也可以使用long类型的数字创建对象。例如:
BigInteger num1 = new BigInteger("123456789");BigInteger num2 = BigInteger.valueOf(987654321);
- 基本运算:
BigInteger类提供了大整数的
加法、减法、乘法、除法和取余
的方法。例如:
BigInteger sum = num1.add(num2);BigInteger difference = num1.subtract(num2);BigInteger product = num1.multiply(num2);BigInteger quotient = num1.divide(num2);BigInteger remainder = num1.remainder(num2);
- 比较大小:
BigInteger类还提供了比较两个大整数的大小的方法,包括等于、大于、小于等。例如:
boolean isEqual = num1.equals(num2);boolean isGreaterThan = num1.compareTo(num2) > 0;boolean isLessThan = num1.compareTo(num2) < 0;
- 转换为其他类型:
BigInteger对象可以转换为其他类型的数据,如int、long、double等。例如:
int intValue = num1.intValue();long longValue = num1.longValue();double doubleValue = num1.doubleValue();
- 幂运算:
BigInteger类提供了计算一个大整数的幂的方法。例如:
BigInteger power = num1.pow(3);
BigInteger类还提供了很多其他的方法,用于处理大整数的运算。
在处理大整数的场景中,使用BigInteger可以避免溢出的问题,且能够进行更灵活的计算。
代码实现:
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;public class Main{public static void main(String[] args) {//测试案例int[] digits = new int[]{7, 2, 8, 5, 0, 9, 1, 2, 9, 5, 3, 6, 6, 7, 3, 2, 8, 4, 3, 7, 9, 5, 7, 7, 4, 7, 4, 9, 4, 7, 0, 1, 1, 1, 7, 4, 0, 0, 6};int[] res = plusOne(digits);System.out.println(Arrays.toString(res));//[7, 2, 8, 5, 0, 9, 1, 2, 9, 5, 3, 6, 6, 7, 3, 2, 8, 4, 3, 7, 9, 5, 7, 7, 4, 7, 4, 9, 4, 7, 0, 1, 1, 1, 7, 4, 0, 0, 7]}public static int[] plusOne(int[] digits) {//大数计算BigInteger num = BigInteger.valueOf(0);//num = 0;BigInteger zero = BigInteger.valueOf(0);//zero = 0;BigInteger numNew;BigInteger ten = BigInteger.valueOf(10);//ten = 10;for (int i = 0; i < digits.length; i++) {//将原数组计算为一个数num = num.multiply(ten).add(new BigInteger(String.valueOf(digits[i])));//num = num*100 + digits[i];}//原数加一numNew = num.add(new BigInteger("1"));//numNew = num+1;ArrayList<Integer> arr = new ArrayList<>();//定义变长数组存储新数的数位数字//新数转成整型数组while (!numNew.equals(zero)) {//numNew != 0BigInteger[] bigIntegers = numNew.divideAndRemainder(ten);//除法计算,可以得到商和余数的数组int ge = bigIntegers[1].intValue();//ge = numNew%10arr.add(ge);//个位放入数组numNew = bigIntegers[0];//nunNew/=10;}int[] res = new int[arr.size()];//结果数组for (int i = 0; i < arr.size(); i++) {res[i] = arr.get(arr.size() - 1 - i);//将arr元素反转之后存入}//返回结果数组return res;}
}
这篇关于66. 加一(Java):BigInteger的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!