415. Add Strings
来源:互联网 发布:韩春雨 知乎 编辑:程序博客网 时间:2024/06/04 19:28
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
- The length of both num1 and num2 is < 5100.
- Both num1 and num2 contains only digits 0-9.
- Both num1 and num2 does not contain any leading zero.
- You must not use any built-in BigInteger library or convert the inputs to integer directly.
两个字符串求和
做出来了 但是不够简洁
discuss里有一个比较优雅
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 || carry == 1; 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; } return sb.reverse().toString(); }}
阅读全文
0 0
- 415. Add Strings
- Leetcode-415. Add Strings
- 415. Add Strings
- 415. Add Strings
- 415. Add Strings
- 415. Add Strings
- LeetCode 415. Add Strings
- 415. Add Strings
- 415. Add Strings
- [LeetCode]--415. Add Strings
- LeetCode 415. Add Strings
- LeetCode 415. Add Strings
- 415. Add Strings
- LeetCode 415. Add Strings
- 415. Add Strings
- 415. Add Strings
- 415. Add Strings(unsolved)
- leetcode 415. Add Strings
- Java数据结构实现之链表
- 49.笔记 MySQL学习——事务处理
- NOIP2017普及组复赛总结
- ctest有n个苹果,要将它放入容量为v的背包。给出第i个苹果的大小和价钱,求出能放入背包的苹果的总价钱最大值。 Input 有多组测试数据,每组测试数据第一行为2个正整数,分别代表苹果的个数n
- JAVA【IO五】转换流
- 415. Add Strings
- 大数据早报:机器人公司优必选获腾讯 4000 万美元 C 轮融资 比特币逼近8000美元再创新高(11.18)
- c++primer 第五版
- 分析非结构化数据的10个步骤
- 设置图列(key/legend)的位置和大小 --gnuplot
- 商机 | 大数据/政务云采购清单 招标7起,最高招标价为850万(11.15-11.17)
- SQL Server安装教程
- 50.笔记 MySQL学习——利用事务处理保证语句
- CSS自适应网站布局媒体查询如何设置断点