两数相加高精度问题

package 有用的方法.精度问题;

import java.util.Scanner;
import java.util.Stack;

public class AAddBInt {


    /**
     * 两个数相加,非常大的数,用string表示
     * @param args
     */
    public static void main(String[] args) {

        Scanner sc =new Scanner(System.in);


        String s1 =sc.next();
        String s2 =sc.next();

        //定义一个
        Stack<Character> stack1 = new Stack<>();
        Stack<Character> stack2 = new Stack<>();

        //先进栈

        char[] c1 = s1.toCharArray();
        char[] c2 = s2.toCharArray();








        if (c1.length>c2.length){
            for (int i = 0; i <c1.length ; i++) {
                stack1.push(c1[i]);
            }

            for (int i = 0; i <c2.length ; i++) {
                stack2.push(c2[i]);
            }
        }else{
            for (int i = 0; i <c1.length ; i++) {
                stack2.push(c1[i]);
            }

            for (int i = 0; i <c2.length ; i++) {
                stack1.push(c2[i]);
            }
        }


        Stack<Integer> stack =new Stack<>();



        int ans=0;
        while (!stack1.empty()){

            Character p1 = stack1.pop();
            Character p2='0';

            if (!stack2.empty()){
                p2 =stack2.pop();
            }
            int sum1;
            if (ans==1){
                sum1=p1-'0'+1;
            }else {
                sum1=p1-'0';
            }

            int sum2=p2-'0';

            if (sum1+sum2>=10){
                stack.push((sum1+sum2)%10);
                ans=1;
            }else {
                stack.push(sum1+sum2);
                ans=0;
            }

        }
        if (ans==1){
            stack.push(1);
        }


        while (!stack.empty()){
            Integer pop = stack.pop();
            System.out.print(pop);
        }


    }


}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值