其他分享
首页 > 其他分享> > 超长非负数求和

超长非负数求和

作者:互联网

 


import java.util.Arrays;
import java.util.Scanner;

public class Demo1 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s1 = sc.nextLine();
		String s2 = sc.nextLine();
		String s = addSum(s1, s2);
		System.out.println(s);
	}

	public static String[] split(String str) {
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) == '.') {
				return new String[] { str.substring(0, i), str.substring(i + 1) };
			}
		}
		return new String[] { str, "" };
	}

	public static String addSum(String s1, String s2) {
		String[] number1 = split(s1);
		String[] number2 = split(s2);

		String Integer1 = number1[0];
		String Integer2 = number2[0];
		String dot1 = number1[1];
		String dot2 = number2[1];

		StringBuilder dotsb1 = new StringBuilder(dot1);
		StringBuilder dotsb2 = new StringBuilder(dot2);
		while (dotsb1.length() != dotsb2.length()) {
			if (dotsb1.length() < dotsb2.length()) {
				dotsb1.append("0");
			} else {
				dotsb2.append("0");
			}
		}

		dotsb1.reverse();
		dotsb2.reverse();
		StringBuilder integerRes = new StringBuilder();
		int len2 = dotsb1.length();
		boolean flag = true;
		int jw = 0;
		for (int i = 0; i < len2; i++) {
			int tmp = jw;
			if (i < dotsb1.length()) {
				tmp = dotsb1.charAt(i) - '0' + tmp;
			}
			if (i < dotsb2.length()) {
				tmp = dotsb2.charAt(i) - '0' + tmp;
			}
			if (tmp >= 10) {
				jw = tmp / 10;
				tmp %= 10;
			} else {
				jw = 0;
			}
			char c = (char) (tmp + '0');
			if (flag && c == '0') {
				continue;
			} else if (c != '0') {
				flag = false;
			}
			integerRes.append(c);
		}
		if (!flag) {
			integerRes.append(".");
		}

		StringBuilder sb1 = new StringBuilder(Integer1);
		sb1.reverse();
		StringBuilder sb2 = new StringBuilder(Integer2);
		sb2.reverse();
		int len1 = sb1.length() > sb2.length() ? sb1.length() : sb2.length();
		for (int i = 0; i < len1; i++) {
			int tmp = jw;
			if (i < sb1.length()) {
				tmp = sb1.charAt(i) - '0' + tmp;
			}
			if (i < sb2.length()) {
				tmp = sb2.charAt(i) - '0' + tmp;
			}
			if (tmp >= 10) {
				jw = tmp / 10;
				tmp %= 10;
			} else {
				jw = 0;
			}
			integerRes.append((char) (tmp + '0'));
		}
		if (jw == 1) {
			integerRes.append('1');
		}
		return integerRes.reverse().toString();
	}
}
输入
1234567890123456789012345678901234567890.1234567890123456789012345678901234567890
1000000000100000000010000000001000000000.1000000000100000000010000000001000000000
输出
2234567890223456789022345678902234567890.223456789022345678902234567890223456789

 

 

标签:tmp,String,求和,StringBuilder,length,负数,int,超长,new
来源: https://blog.csdn.net/qq_40685275/article/details/98965802