【CT】LeetCode手撕—415. 字符串相加

目录

  • 题目
  • [1- 思路](#1- 思路)
  • [2- 实现](#2- 实现)
    • [⭐415. 字符串相加------题解思路](#⭐415. 字符串相加——题解思路)
  • [3- ACM 实现](#3- ACM 实现)

题目


1- 思路

  • 模式识别:字符串相加

逆向遍历过程模拟

  • 数据结构 ① String res :记录res② carry 记录进位值
  • ① 定义两个整数遍历 nums1nums2 ------>index1 = nums1.length,index2 - nums2.length
  • ② 利用 while循环遍历 while( index1>=0 || index2>=0 || carry != 0)
  • ③ 定义 x = index1>=0 ? nums1.charAt(i) - '0' : 0;
  • 同理 y = index2>=0 ? nums1.charAt(i) - '0' : 0;
  • 计算 int res = x+y+carry; 之后通过 StringBuffer ans = new StringBuffer(); sb.append(res%10)
  • carry = res/10 ,之后 index1--; index2--;
  • ④ 最终答案 revers

2- 实现

⭐415. 字符串相加------题解思路

java 复制代码
class Solution {
    public String addStrings(String num1, String num2) {
        int index1 = num1.length()-1;
        int index2 = num2.length()-1;

        int carry = 0;
        StringBuffer ans = new StringBuffer();
        // 逆向遍历
        while(index1>=0 || index2>=0  || carry!=0){
            int x = index1>=0 ? num1.charAt(index1) - '0' :0;
            int y = index2>=0 ? num2.charAt(index2) - '0' :0;
            int res = x+y+carry;
            ans.append(res%10);
            carry = res/10;
            index1--;
            index2--;
        }
        ans.reverse();
        return ans.toString();
    }
}

3- ACM 实现

java 复制代码
public class addString {


    public static String addTwo(String num1,String num2){
        int index1 = num1.length()-1;
        int index2 = num2.length()-1;

        int carry = 0;
        StringBuffer ans = new StringBuffer();
        // 遍历
        while( index1 >=0 || index2>= 0 || carry!=0){
            int x = index1>=0 ? num1.charAt(index1)-'0' : 0;
            int y = index2>=0 ? num2.charAt(index2)-'0' : 0;
            int res = x+y+carry;
            ans.append(res%10);
            carry = res/10;
            index1--;
            index2--;
        }
        ans.reverse();
        return ans.toString();
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("输入str1");
        String input1 = sc.next();
        System.out.println("输入str2");
        String input2 = sc.next();
        System.out.println("相加的结果是"+addTwo(input1,input2));
    }
}

相关推荐
荆棘鸟智能7 小时前
城市感知设备怎么统一接入?从多协议网关到设备模型的中间件架构设计
人工智能·算法·边缘计算
INGNIGHT11 小时前
270 · 电话号码的字母组合II(Trie)
linux·算法
2401_8390805411 小时前
C++常见八股
数据结构·c++·算法
青山是哪个青山11 小时前
LeetCode 188:买卖股票的最佳时机 IV
算法
mikuyyds12 小时前
geo-toolbox 插件算法解析:RUSLE 与 MUSLE 的工程化落地
算法·rust·gis
Tisfy12 小时前
LeetCode 3498.字符串的反转度:一次遍历
leetcode·字符串·题解·遍历
a1879272183112 小时前
【算法】树(二):队列与祖先——BFS 骨架三配件、短路透传与合流
算法·leetcode·二叉树··bfs·算法讲解·树遍历
syagain_zsx12 小时前
算法基础篇 · 03 枚举(C++ 题解)
c++·算法·二进制·枚举
weixin_3077791313 小时前
C++代码实现MATLAB中的ode23tb函数功能
开发语言·c++·算法·matlab
我是章汕呐13 小时前
地级市能源消耗量及消耗强度数据【2006-2023年】平衡面板
人工智能·经验分享·算法·回归