Multiply Strings (Java)
来源:互联网 发布:大数据 入门书籍 编辑:程序博客网 时间:2024/06/07 01:43
Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
先把每一位乘出来的数存起来,然后再集体处理进位。
Source
public class Solution { public String multiply(String num1, String num2) { if(num1.equals("0") || num2.equals("0")) return "0"; StringBuffer x1 = new StringBuffer(num1); StringBuffer x2 = new StringBuffer(num2); x1.reverse();//大数乘法一般都倒过来存,比较好处理 尤其是两个数位数不一样时 x2.reverse();//如果不reverse的话 数组第0位存的是最高位 int[] num = new int[x1.length() + x2.length()]; //相乘,数组要开的大 for(int i = 0; i < x1.length(); i++){ int a = x1.charAt(i) - '0';//***注意减去0 for(int j = 0; j < x2.length(); j++){ int b = x2.charAt(j) - '0'; num[i + j] += a * b; } } StringBuffer res = new StringBuffer(); for(int i = 0; i < num.length; i++){ int temp = num[i] % 10; int carry = num[i] / 10; res.insert(0, temp);//正着存 if(i < num.length - 1) num[i + 1] += carry; } while(res.charAt(0) == '0'){ res.deleteCharAt(0); } return res.toString(); }}
Test
public static void main(String[] args){ String num1 = "1"; String num2 = "2"; System.out.println(new Solution().multiply(num1, num2)); }
0 0
- [Leetcode] Multiply Strings (Java)
- Multiply Strings (Java)
- [LeetCode][Java] Multiply Strings
- [letecode Java] Multiply Strings
- LeetCode : Multiply Strings (java)
- leetcode:Multiply Strings(JAVA)
- Multiply Strings leetcode java
- [leetcode-43]Multiply Strings(java)
- (Java)LeetCode-43. Multiply Strings
- [LeetCode-Java]43. Multiply Strings
- [leetcode]43. Multiply Strings@Java
- [3]43. Multiply Strings(Java)
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- Multiply Strings
- android opencv学习第二天
- [leetcode] Maximal Rectangle
- linux驱动之Hello world
- 字符串的排列和组合
- 初探CAS
- Multiply Strings (Java)
- T-SQL查询:CTE - with as 子句的特殊应用
- 启动Storm集群时碰到的Supervisor反复重启问题
- ios图片动画
- HPU1288 矩阵翻硬币 【大数】
- 关于Linux kernel学习,从epoll切入
- syntax highlighting in LESS command on Ubuntu
- centOS6.5在VMware虚拟机中的网络配置问题
- C# 编写自定义 IP 输入框控件