LeetCode 415. Add Strings

本文解析了LeetCode 415题AddStrings的解决方案,该题要求不使用内置大数库直接计算两个字符串形式的大整数之和。文章详细介绍了如何将字符串转换为数字数组并实现逐位相加及进位处理。

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

LeetCode 415. Add Strings

题目要求:
Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.

这个方法比较复杂,当然效果也不是很高.
但是第一次想到的,首先写上,以后再继续优化

public class solution_new {
    public String addStrings(String num1, String num2) {
        if(num1.equals("0") && num2.equals("0")) return "0";
        int[] arr = new int[Math.max(num1.length(), num2.length()) + 1];
        StringBuffer sb = new StringBuffer();
        arr = tonum(num1, num2);
        if(arr[0] == 0) {
            for(int i = 1;i < arr.length; i++) {
                sb.append(arr[i]);
            }
        }
        else {
            for(int index : arr) {
                sb.append(index);
            }
        }
        return sb.toString();
    }

    public int[] tonum(String num1, String num2) {

        //首先创建数组,进行数据的存储
        int[] arr = new int[Math.max(num1.length(), num2.length())];
        int i = Math.max(num1.length(), num2.length()) - 1;
        for(int c = num1.length() - 1; c >= 0; c--) {
            arr[i--] = num1.charAt(c) - '0' + 0;
        }
        i = Math.max(num1.length(), num2.length()) - 1;
        for(int c = num2.length() - 1; c >= 0; c--) {
            arr[i--] += num2.charAt(c) - '0' + 0;
        }

        //数组循环进位
        for(i = arr.length - 1; i >= 0; i--) {
            if(arr[i] > 9) {
                if(i == 0) {
                    //整个数组进位
                    int[] arrx = new int[arr.length + 1];
                    arrx[0] = 1;
                    arr[i] -= 10;
                    System.arraycopy(arr, 0, arrx, 1, arr.length);
                    return arrx;
                }
                else {
                    //在原数组上进行改动
                    arr[i] -= 10;
                    arr[i-1] += 1;
                }
            }
        }
        return arr;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ncst

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值