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

相关推荐
艾莉丝努力练剑26 分钟前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
_殊途2 小时前
《Java HashMap底层原理全解析(源码+性能+面试)》
java·数据结构·算法
珊瑚里的鱼5 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
秋说6 小时前
【PTA数据结构 | C语言版】顺序队列的3个操作
c语言·数据结构·算法
lifallen7 小时前
Kafka 时间轮深度解析:如何O(1)处理定时任务
java·数据结构·分布式·后端·算法·kafka
liupenglove7 小时前
自动驾驶数据仓库:时间片合并算法。
大数据·数据仓库·算法·elasticsearch·自动驾驶
python_tty8 小时前
排序算法(二):插入排序
算法·排序算法
然我8 小时前
面试官:如何判断元素是否出现过?我:三种哈希方法任你选
前端·javascript·算法
F_D_Z9 小时前
【EM算法】三硬币模型
算法·机器学习·概率论·em算法·极大似然估计
秋说9 小时前
【PTA数据结构 | C语言版】字符串插入操作(不限长)
c语言·数据结构·算法