【Java】大数加法-不使用Biginteger类,用数组模拟运算

题目

数组模拟加法运算
数据范围1~3e30

注释

  • @Title 大数加法.java
  • @author Baisu
  • @date 2019年10月28日
  • @version 1.0

说明

版本1.0,还没开始优化,后续可能会优化代码

Java源代码

import java.util.*;

/**
 * @Title 大数加法.java
 * @author Baisu
 * @date 2019年10月28日
 * @version 1.0
 */

public class 大数加法 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		//声明字符串变量
		String s1 = new String();
		String s2 = new String();
		//输入大数字符串
		s1 = sc.nextLine();
		s2 = sc.nextLine();
		//字符串存储到数组
		char c1[] =s1.toCharArray();
		char c2[] =s2.toCharArray();
		//声明整型数组变量
		int a1 [] = new int [60];
		int a2 [] = new int [60];
		//字符数组转化为整数数组
		for(int i=0; i<c1.length; i++) {
			a1[c1.length-i-1] = c1[i];
			a1[c1.length-i-1]-=48;
		}
		for(int i=0; i<c2.length; i++) {
			a2[c2.length-i-1] = c2[i];
			a2[c2.length-i-1]-=48;
		}
		//声明整型数组存储结果
		int a3 [] = new int [60];
		//计算结果
		for(int i=0; i<40; i++) {
			a3[i] += a1[i] + a2[i];
			if(a3[i]>=10) {
				a3[i]%=10;
				a3[i+1]++;
			}
		}
		//输出结果
		int b = 0;
		for(int i=40; i>=0; i--) {
			if(a3[i]!=0) {
				b=i;
				break;
			}
		}
		for(int i=b; i>=0; i--) {
			System.out.print(a3[i]);
		}
	}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值