leetcode415---字符串大数相加
字符串 --- 相加 大数
2023-09-27 14:29:12 时间
Given two non-negative numbers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
我的第一个想法就是选好两个字符串,然后模拟加法进位,然后用一个字符串接着,同时记住进位,最后返回这个字符串的反转即可。
没有想到什么比较好的解决思路
public class Solution { public String addStrings(String num1, String num2) { StringBuilder sb = new StringBuilder(); int carry = 0; for(int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0; i--, j--){ int x = i < 0 ? 0 : num1.charAt(i) - '0'; int y = j < 0 ? 0 : num2.charAt(j) - '0'; sb.append((x + y + carry) % 10); carry = (x + y + carry) / 10; } if(carry != 0) sb.append(carry); return sb.reverse().toString(); } }
相关文章
- 教你如何进行数仓字符串、二进制、十六进制互转
- thymeleaf:字符串拼接+输出单引号
- php判断字符串是否是json格式
- 拆分字符串为单一字符
- Java中字符串中连续相同字符去重方法
- oracle 11g 版本之前,创建自定义函数--解析JSON字符串.sql
- spring mvc 页面的请求参数获取以及响应-------2.直接返回将要渲染的字符串数据
- 第83天:NumPy 字符串操作
- Oracle截取字符串和查找字符串
- Python生成一个不含回文字符串的字符串
- ios上获取字符串指定字符集对应的字节码
- Python 利用字符串切片实现文本内容加密及解密
- joomla librariesjoomlasessionsession.php 反序列化截断畸形字符串导致对象注入漏洞
- C++宽字符串转字符串