43. Multiply Strings
2016-02-29 03:34
246 查看
把两个数反过来算
ref: https://zhongyinzhang.wordpress.com/2014/03/13/multiply-strings/r
public String multiply(String num1, String num2) { if(num1 == null || num1.length() == 0 || num2 == null || num2.length() == 0) { return ""; } if(num1.equals("0") || num2.equals("0")) { return "0"; } StringBuilder n1 = new StringBuilder(num1); n1 = n1.reverse(); StringBuilder n2 = new StringBuilder(num2); n2 = n2.reverse(); int[] digit = new int[num1.length()+ num2.length() - 1]; for(int i = 0; i < n1.length(); i++) { for(int j = 0; j < n2.length(); j++) { digit[i + j] += ((int)n1.charAt(i)- '0') * ((int)n2.charAt(j) - '0'); } } int carry = 0; StringBuilder res = new StringBuilder(); for(int i = 0 ; i < digit.length; i++) { System.out.println(digit[i]); } for(int i = 0; i < digit.length; i++) { int temp = digit[i] + carry; res.insert(0, temp % 10); carry = temp / 10; } if(carry != 0) { res.insert(0, carry); } int i = 0; while(i < res.length() && res.charAt(i) == '0') { res.deleteCharAt(i); } return res.toString().equals("") ? "": res.toString(); }
ref: https://zhongyinzhang.wordpress.com/2014/03/13/multiply-strings/r
相关文章推荐
- 【Android】15.1 后台任务和前台任务
- LeetCode Walls and Gates
- Zenefits 第一轮编程题
- 异步处理的深入研究 一
- 串-第4章-《数据结构题集》答案解析-严蔚敏吴伟民版
- mysql
- [Hapi.js] POST and PUT request payloads
- [Hapi.js] View engines
- Cocoapods系列教程(三)——私有库管理和模块化管理
- [转]Learn SQLite in 1 hour
- PythonScript_demo--搭建PXE服务器
- poj 3225 Help with Intervals 线段树lazy-tag求解区间运算
- Beaglebone Black – 连接 GY-91 MPU9250+BMP280 九轴传感器(1)
- css animation 兼容360浏览器
- keepalive配置mysql自动故障转移
- 让web应用正常显示ios输入法表情
- Java的证书:HTTPS与SSL
- QT基本数据类型
- java keytool证书工具使用小结(转)
- 如何让自己的web应用支持iOS表情