首页 > 其他分享 >字符串相加

字符串相加

时间:2022-11-29 14:44:47浏览次数:30  
标签:num1 num2 int res 相加 add 字符串

字符串相加

一、题目描述

给定两个字符串形式的非负数num1he num2,计算它们的和并以字符串的形式返回。不能使用任何的内建函数。
示例1:

输入:num1 = "11", num2 = "123"
输出:"134"

示例2:

输入:num1 = "456", num2 = "77"
输出:"533"

示例3

输入:num1 = "0", num2 = "0"
输出:"0"

二、解题思路

可以考虑使用使用竖式加法,类似于我们在纸上计算的加法那样。为了解决两个字符串位数不同的情况,可以给简短位数补零来处理对位数不齐的情况。

三、解题方法

方法1
使用两个指针分别指向两个字符串的尾,在用一个变量add来记录加时的进位。循环遍历两个字符串。利用ASCII编码的特性,来计算出字符,并存入StringBuffer中,最后将流反转再转为字符串即可。
代码实现:

class Solution {
    public String addStrings(String num1, String num2) {

        int i = num1.length()-1;
        int j = num2.length()-1;
        int add = 0;

        StringBuffer res = new StringBuffer();
        while(i >= 0 || j >= 0 || add!=0){

            int x = i >= 0 ? num1.charAt(i) - '0' : 0;
            int y = j >= 0 ? num2.charAt(j) - '0' : 0;

            int result = x + y + add;
            res.append(result%10);
            add = result/10;

            i--;
            j--;
        }

        res.reverse();
        return res.toString();
    }
}

标签:num1,num2,int,res,相加,add,字符串
From: https://www.cnblogs.com/zjjtt/p/16935357.html

相关文章