Add Strings
来源:互联网 发布:c语言结构体链表 编辑:程序博客网 时间:2024/05/16 10:45
题目地址:https://leetcode.com/problems/add-strings/
Given two non-negative numbers 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.
题目要将两个数字字符串转换为数字,然后相加,得出结果,再转换为字符串。题目第四条说的很明确,不能用内置的转换方法,要是可以,那不就太简单了么。
题目本身没啥难度,关键是进位处理,这一点都考虑到了,也就没啥问题了。
public class AddStrings { public String addStrings(String num1, String num2) { StringBuilder result = new StringBuilder(""); //进位标记 boolean carry = false; for (int i = num1.length() - 1, j = num2.length() - 1 ; i >= 0 && j >= 0; i--, j--) { int t = 0; if (carry) t = num1.charAt(i) - '0' + num2.charAt(j) - '0' + 1; else t = num1.charAt(i) - '0' + num2.charAt(j) - '0'; if (t >= 10) carry = true; else carry = false; if (carry) result.insert(0, String.valueOf((char)('0' + (t-10)))); else result.insert(0, String.valueOf((char)('0' + t))); } // 不等长的时候,余下的位的计算,注意这里也有可能产生进位。 if (num1.length() > num2.length()) { for (int i = num1.length() - num2.length() - 1; i >= 0; i--) { int t = 0; if (carry) t = num1.charAt(i) - '0' + 1; else t = num1.charAt(i) - '0'; if (t >= 10) carry = true; else carry = false; if (carry) result.insert(0, String.valueOf((char)('0' + (t-10)))); else result.insert(0, String.valueOf((char)('0' + t))); } } if (num2.length() > num1.length()) { for (int i = num2.length() - num1.length() - 1; i >= 0; i--) { int t = 0; if (carry) t = num2.charAt(i) - '0' + 1; else t = num2.charAt(i) - '0'; if (t >= 10) carry = true; else carry = false; if (carry) result.insert(0, String.valueOf((char)('0' + (t-10)))); else result.insert(0, String.valueOf((char)('0' + t))); } } if (carry) result.insert(0, '1'); return result.toString(); } public static void main(String[] args) { AddStrings addStrings = new AddStrings(); System.out.println(addStrings.addStrings("999929", "72")); }}
时间复杂度为:O(max{m, n}),其中m和n分别是两个字符串的长度。
0 0
- Add Strings
- Add Strings
- Add Strings
- Add Strings
- Add Strings
- Add Strings
- Add Strings
- 415. Add Strings
- Leetcode 415 Add Strings
- Leetcode-415. Add Strings
- 415. Add Strings
- leetcode_415 Add Strings
- 415 add strings
- LeetCode[415] Add Strings
- 415. Add Strings
- LeetCode #415: Add Strings
- 415. Add Strings
- 415. Add Strings
- Activity之间传递数据的方法总结
- 678.最小K个数之和
- CSS3属性transform详解之(旋转:rotate,缩放:scale,倾斜:skew,移动:translate)
- 各种排序算法的java实现及时间、空间复杂度、稳定程度总结
- Delphi的菜单加速键
- Add Strings
- PTA数据结构与算法题目集(中文)4-10 二分查找 (20分)
- Spring 框架知识知识总结
- TCP的三次握手
- [小技巧] virtualbox共享文件夹无访问权限问题解决方法
- S3.1_Struts2_BasicConfiguration struts2主要配置文件和常用配置还有中文乱码问题以及简单验证
- Npgsql使用入门(三)【批量导入数据】
- Material Design风 第二话(CollapsingToolbarLayout+AppBarLayout+NestedScrollView)
- Hibernate中get和load的区别