Java基于Lambda实现BigInteger运算接口与数位乘积开发问题
实现代码及说明
1. 已写代码正确性确认
你当前编写的三个BigOperation接口的方法引用实现完全符合要求,等价于标准Lambda写法:
BigOperation op1 = (x, y) -> x.multiply(y); // 对应乘法 BigOperation op2 = (x, y) -> x.divide(y); // 对应除法 BigOperation op3 = (x, y) -> x.remainder(y); // 对应取余
2. 核心逻辑说明
获取BigInteger每一位的逻辑:
- 用
op3(取余)和数值10做运算,得到当前个位数字 - 用
op2(除法)和数值10做运算,去掉当前个位数字 - 循环/递归直到数值变为0,过程中用
op1(乘法)累积所有数位的乘积
3. 完整实现代码
import java.math.BigInteger; import java.util.Random; interface BigOperation{ BigInteger operation(BigInteger x, BigInteger y); } public class LearningBigInteger { // 迭代版本实现 static BigInteger productIterative(BigInteger n, BigOperation op1, BigOperation op2, BigOperation op3){ BigInteger product = BigInteger.ONE; BigInteger ten = BigInteger.TEN; // 处理0的特殊情况 if(n.equals(BigInteger.ZERO)){ return BigInteger.ZERO; } BigInteger temp = n.abs(); // 忽略符号位 while (temp.compareTo(BigInteger.ZERO) > 0){ // 取当前个位 BigInteger digit = op3.operation(temp, ten); // 乘入结果 product = op1.operation(product, digit); // 遇到0可以提前结束,乘积已经是0 if(product.equals(BigInteger.ZERO)){ break; } // 去掉个位 temp = op2.operation(temp, ten); } return product; } // 递归版本实现 static BigInteger productRecursive(BigInteger n, BigOperation op1, BigOperation op2, BigOperation op3){ BigInteger ten = BigInteger.TEN; BigInteger temp = n.abs(); // 递归终止条件:数值为0返回1 if(temp.compareTo(BigInteger.ZERO) == 0){ return BigInteger.ONE; } // 取当前个位 BigInteger digit = op3.operation(temp, ten); // 个位为0直接返回0,无需继续递归 if(digit.equals(BigInteger.ZERO)){ return BigInteger.ZERO; } // 递归计算剩余数位的乘积,和当前数位相乘返回 return op1.operation(digit, productRecursive(op2.operation(temp, ten), op1, op2, op3)); } public static void main(String[] args) { // Lambda实现三个运算 BigOperation op1 = BigInteger::multiply; BigOperation op2 = BigInteger::divide; BigOperation op3 = BigInteger::remainder; // 测试题目给定示例 BigInteger[] testCases = { new BigInteger("8584803"), new BigInteger("12345"), new BigInteger("234"), BigInteger.ZERO, new BigInteger("999"), BigInteger.valueOf(Math.abs(new Random().nextInt())) // 随机数测试 }; for (BigInteger num : testCases) { System.out.println("Given big integer " + num); System.out.println("(Iterative) " + productIterative(num, op1, op2, op3)); System.out.println("(Recursive) " + productRecursive(num, op1, op2, op3)); System.out.println("------------------------"); } } }
4. 输出验证
运行后会输出所有测试用例的结果,其中题目要求的示例输出完全匹配:
Given big integer 8584803 (Iterative) 0 (Recursive) 0 ------------------------ Given big integer 12345 (Iterative) 120 (Recursive) 120 ------------------------
内容的提问来源于stack exchange,提问作者Bryead
相关产品推荐
相关产品推荐

