当前位置:网站首页>LeetCode 415:字符串相加
LeetCode 415:字符串相加
2022-08-01 07:03:00 【斯沃福德】
题目:
思路:
和数字相加一样的过程,双指针从后指向前遍历;
两数和大于10则记录在carry中并向前传递,即每次temp要加上carry的值;
追加到结果时,每次只添加个数,所以是 temp%10;
若 i和j 都遍历完跳出while,carray依然为1,即还需要再添加一个1;
最后要将结果reverse()逆序;
注意:
使用charAt(i) -‘0’ 将 char类型转变为int 类型,但是只能是减, 不能是 + ’0 ‘ !
class Solution {
public String addStrings(String num1, String num2) {
// 双指针 i j 指向字符串最后一位;
// i j 指向的加起来大于10 ,则进位 carry
// 从末尾开始加,则最后需要逆序
// 双指针
StringBuilder r=new StringBuilder("");
int i=num1.length()-1;
int j=num2.length()-1;
int carry=0; // 进位
while(i>=0 || j>=0){
int n1= i>=0 ? num1.charAt(i)-'0': 0; // char减 '0' 可以得到int的结果!
int n2= j>=0 ? num2.charAt(j)-'0': 0;
int temp=n1+n2+carry;
carry=temp/10; // carry为0 或 1
r.append(temp%10);
i--;
j--;
}
if(carry==1){
r.append("1");
}
return r.reverse().toString();
}
}
边栏推荐
- MATLAB program design and application of MATLAB 2.5
- Offer刷题——1
- WebSocket implements chat function
- Sound Signal Processing Fundamental Frequency Detection and Time-Frequency Analysis
- 插入排序—直接插入排序和希尔排序
- first unique character in characters
- Golang:go模版引擎的使用
- Jupyter shortcuts
- Introduction to the basic principles, implementation and problem solving of crawler
- Dbeaver connect the MySQL database and error Connection refusedconnect processing
猜你喜欢
MATLAB程序设计与应用 2.5 MATLAB运算
Srping中bean的生命周期
Introduction to the basic principles, implementation and problem solving of crawler
sum of special numbers
first unique character in characters
拳头游戏免版权音乐下载,英雄联盟无版权音乐,可用于视频创作、直播
【音视频】srs直播平台搭建
小程序通过云函数操作数据库【使用get取数据库】
Detailed explanation of the crawler framework Scrapy
Dart 异常详解
随机推荐
问下 mysql向pg同步多个表的话 有什么好的方案吗?
对于升级go1.18的goland问题
Bean的生命周期
NUMPY
湖仓一体电商项目(一):项目背景和架构介绍
WebSocket implements chat function
拳头游戏免版权音乐下载,英雄联盟无版权音乐,可用于视频创作、直播
上课作业(7)——#598. 取余运算(mod)
Srping中bean的生命周期
小程序通过云函数操作数据库【使用get取数据库】
LeetCode 0150. 逆波兰表达式求值
Self-made a remote control software - VeryControl
监听父元素宽高,自适应插件大小
特别数的和
More than 2022 cattle guest school game 4 yue
戴尔PowerEdge服务器R450 RAID配置步骤
MySQL row locks and gap locks
从零开始—仿牛客网讨论社区项目(一)
数据湖:数据同步工具NiFi
weight distribution