牛客 剑指offer:大数加法

本文介绍了一种处理大数加法的有效算法。通过逆向遍历字符串表示的大数,并模拟传统的加法过程来实现两个大数相加。文章详细展示了如何处理进位以及不同长度的数字相加等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:大数加法

思路:

模拟加法即可。

代码:

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 计算两个数之和
     * @param s string字符串 表示第一个整数
     * @param t string字符串 表示第二个整数
     * @return string字符串
     */
    public String solve (String s, String t) {
        // write code here
        int lens = s.length() - 1;
        int lent = t.length() - 1;
        StringBuilder res = new StringBuilder();
        int add = 0;
        while (lens >= 0 && lent >= 0) {
            int a = s.charAt(lens) - '0';
            int b = t.charAt(lent) - '0';
            int temp = (a + b + add) % 10;
            add = (a + b + add) / 10;
            res.append(String.valueOf(temp));
            lens --;
            lent --;
        }
        while (lens >= 0) {
            int a = s.charAt(lens) - '0';
            int temp = (a + add) % 10;
            add = (a + add) / 10;
            res.append(String.valueOf(temp));
            lens --;
        }
        while (lent >= 0) {
            int b = t.charAt(lent) - '0';
            int temp = (b + add) % 10;
            add = (b + add) / 10;
            res.append(String.valueOf(temp));
            lent --;
        }
        if (add > 0) {
            res.append(String.valueOf(add));
        }
        return res.reverse().toString();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值