当前位置:网站首页>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();
}
}
边栏推荐
猜你喜欢

我说过无数遍了:从来没有一种技术是为灵活组合这个目标而设计的

升级为重量级锁,锁重入会导致锁释放?

信息系统项目管理师必背核心考点(五十六)配置控制委员会(CCB)的工作

爬虫框架 Scrapy 详解

matlab simulink 粒子群优化模糊pid控制的电机泵

Matlab simulink particle swarm optimization fuzzy pid control motor pump

对于升级go1.18的goland问题

Data organization -- singly linked list of the linear table

【FiddlerScript】利用FiddlerScript抓包保利威下载

数据机构----线性表之单向链表
随机推荐
crypto-js uses
滚动条样式修改
The BP neural network based on MATLAB voice characteristic signal classification
WebSocket implements chat function
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
Go 支持 OOP: 用 struct 代替 class
curl (7) Failed connect to localhost8080; Connection refused
表的创建、修改与删除
JS的运行原理
「游戏引擎 浅入浅出」4.1 Unity Shader和OpenGL Shader
实战演练 Navicat 中英文模式切换
仿牛客网讨论社区项目—项目总结及项目常见面试题
插入排序—直接插入排序和希尔排序
Golang:go获取url和表单属性值
头歌MySQL数据库实训答案 有目录
LeetCode240+312+394
MySQL row locks and gap locks
奇葩问题 npm install 报错 gyp ERR
我三本学历,五面阿里,被面试官“供”着出来了,拿了33*15的Offer
基于百度OCR的网站验证码在线识别