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

相关推荐
j_xxx404_1 小时前
数据结构:栈和队列力扣算法题
c语言·数据结构·算法·leetcode·链表
南莺莺1 小时前
假设一个算术表达式中包含圆括号、方括号和花括号3种类型的括号,编写一个算法来判别,表达式中的括号是否配对,以字符“\0“作为算术表达式的结束符
c语言·数据结构·算法·
Lris-KK2 小时前
【Leetcode】高频SQL基础题--180.连续出现的数字
sql·leetcode
THMAIL2 小时前
深度学习从入门到精通 - 神经网络核心原理:从生物神经元到数学模型蜕变
人工智能·python·深度学习·神经网络·算法·机器学习·逻辑回归
珍珠是蚌的眼泪2 小时前
LeetCode_位运算
leetcode·位运算·异或·韩明距离·数字的补数
野犬寒鸦2 小时前
力扣hot100:旋转图像(48)(详细图解以及核心思路剖析)
java·数据结构·后端·算法·leetcode
墨染点香2 小时前
LeetCode 刷题【61. 旋转链表】
算法·leetcode·职场和发展
岁忧2 小时前
(LeetCode 面试经典 150 题) 200. 岛屿数量(深度优先搜索dfs || 广度优先搜索bfs)
java·c++·leetcode·面试·go·深度优先
一枝小雨2 小时前
【OJ】C++ vector类OJ题
数据结构·c++·算法·leetcode·oj题
Tisfy3 小时前
LeetCode 3516.找到最近的人:计算绝对值大小
数学·算法·leetcode·题解