【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));
    }
}

相关推荐
董董灿是个攻城狮3 小时前
5分钟搞懂什么是窗口注意力?
算法
Dann Hiroaki3 小时前
笔记分享: 哈尔滨工业大学CS31002编译原理——02. 语法分析
笔记·算法
qqxhb5 小时前
零基础数据结构与算法——第四章:基础算法-排序(上)
java·数据结构·算法·冒泡·插入·选择
FirstFrost --sy6 小时前
数据结构之二叉树
c语言·数据结构·c++·算法·链表·深度优先·广度优先
森焱森6 小时前
垂起固定翼无人机介绍
c语言·单片机·算法·架构·无人机
搂鱼1145147 小时前
(倍增)洛谷 P1613 跑路/P4155 国旗计划
算法
Yingye Zhu(HPXXZYY)7 小时前
Codeforces 2021 C Those Who Are With Us
数据结构·c++·算法
无聊的小坏坏8 小时前
三种方法详解最长回文子串问题
c++·算法·回文串
长路 ㅤ   8 小时前
Java后端技术博客汇总文档
分布式·算法·技术分享·编程学习·java后端
秋说8 小时前
【PTA数据结构 | C语言版】两枚硬币
c语言·数据结构·算法