加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

大数相乘

发布时间:2020-12-14 02:16:48 所属栏目:大数据 来源:网络整理
导读:很久之前就想写这个程序了,但是当时水平有限,思想也有限,找同学要了一份代码,当时也没看懂,后来就不了了知了。昨天晚上辗转难以入眠,突然想起此事,手机查了一下,了解了运算的思想,于是现在就写了起来。 通过网上的资料,我也没有看太多,就那么一份

很久之前就想写这个程序了,但是当时水平有限,思想也有限,找同学要了一份代码,当时也没看懂,后来就不了了知了。昨天晚上辗转难以入眠,突然想起此事,手机查了一下,了解了运算的思想,于是现在就写了起来。

通过网上的资料,我也没有看太多,就那么一份,大致的思想就是模拟手算,通过数组存放待运算的数字。既然有了思想,那么就自己动手了,代码实现起来比较简单,就是纯粹的模拟手工运算而已。代码如下:


package com.fly.cal;

import java.util.Scanner;

public class Bigmx {
	public static void main(String[] args) {
		String[] str = getBigNums();
		String sum = calcBigNum(str);
		System.out.println(sum);
	}
	/*
	 * 获取待计算数字
	 */
	public static String[] getBigNums() {
		String[] st = new String[2];
		Scanner scan = new Scanner(System.in);
		System.out.print("请输入第1个:");
		st[0] = scan.nextLine();
		System.out.print("请输入第2个:");
		st[1] = scan.nextLine();
		System.out.println("ok");
		return st;
	}
	/*
	 * 计算乘积
	 */
	public static String calcBigNum(String[] s) {
		String s1 = s[0];
		String s2 = s[1];
		int[] sum = new int[s1.length() + s2.length()];
		char[] c1 = s1.toCharArray();
		char[] c2 = s2.toCharArray();
		int counti = 0;
		//运算
		for(int i=c2.length-1; i >= 0 ; i--) {
			int tempc2 = Integer.parseInt(c2[i] + "");
			int countj = 0;
			for(int j=c1.length-1; j >= 0; j--) {
				int tempc1 = Integer.parseInt(c1[j] + "");
				sum[counti + countj] += tempc2 * tempc1;
				countj++;
			}
			counti++;
		}
		//整理结果大于10
		for(int i=0; i<sum.length; i++) {
			if(sum[i] >= 10) {
				sum[i+1] += sum[i] / 10;
				sum[i] = sum[i] % 10;
			}
		}
		//转换结果
		StringBuilder sb = new StringBuilder();
		for(int i=0; i<sum.length; i++) {
			sb.append(sum[i]);
		}
		String ssum = sb.reverse().toString();
		while(ssum.startsWith("0")) {
			ssum = ssum.substring(1);
		}
		return ssum;
	}
	
}




(注:本程序仅处理非负整数)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读