当前位置:网站首页>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();
}
}
边栏推荐
- Jupyter shortcuts
- Vim扩展内容
- Information system project managers must recite the work of the core test site (56) Configuration Control Board (CCB)
- 数据湖:数据同步工具NiFi
- 点餐系统数据库设计--SQL Server
- curl (7) Failed connect to localhost8080; Connection refused
- 小程序通过云函数操作数据库【使用get取数据库】
- Self-made a remote control software - VeryControl
- More than 2022 cattle guest school game 4 yue
- Three aspects of Ali: How to solve the problem of MQ message loss, duplication and backlog?
猜你喜欢
Vim三种模式
从底层结构开始学习FPGA(6)----分布式RAM(DRAM,Distributed RAM)
奇葩问题 npm install 报错 gyp ERR
阿里三面:MQ 消息丢失、重复、积压问题,该如何解决?
插入排序—直接插入排序和希尔排序
Matlab simulink particle swarm optimization fuzzy pid control motor pump
实战演练 Navicat 中英文模式切换
MATLAB program design and application of MATLAB 2.5
响应式织梦模板园林花卉类网站
Srping bean in the life cycle
随机推荐
声音信号处理基频检测和时频分析
Information system project managers must recite the work of the core test site (56) Configuration Control Board (CCB)
return;代表含义
Dbeaver connect the MySQL database and error Connection refusedconnect processing
matlab simulink 粒子群优化模糊pid控制的电机泵
2022.7.26 Mock Competition
问下 mysql向pg同步多个表的话 有什么好的方案吗?
监听父元素宽高,自适应插件大小
MATLAB程序设计与应用 2.5 MATLAB运算
【一句话攻略】彻底理解JS中的回调(Callback)函数
first unique character in characters
奇葩问题 npm install 报错 gyp ERR
Practical training Navicat Chinese and English mode switching
Matlab simulink particle swarm optimization fuzzy pid control motor pump
Dart exception details
Guest brush SQL - 2
matlab wind speed model wavelet filtering
数据湖:数据同步工具NiFi
Why is the lightweight VsCode used more and more?Why eat my C drive 10G?How to Painlessly Clean VsCode Cache?Teach you how to lose weight for C drive
"By sharing" northwestern university life service | | bytes a second interview on three sides by HR