Sum—LeetCode-43 Multiply Strings
来源:互联网 发布:8kg.tv域名 编辑:程序博客网 时间:2024/05/25 23:28
题目描述:
Given two non-negative integers num1 andnum2 represented as strings, return the product ofnum1 and num2.
Note:
- The length of both num1 andnum2 is < 110.
- 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 orconvert the inputs to integer directly.
public String multiply(String num1, String num2) { char[] chars1 = num1.toCharArray(); char[] chars2 = num2.toCharArray(); char[][] data = new char[num2.length()][num1.length() + num2.length()]; for(int m = 0; m < num2.length(); ++m){ for(int n = 0; n < num1.length() + num2.length(); ++n){ data[m][n] = '0'; } } int back = 0; for(int i = chars2.length - 1; i >= 0; --i){ int k = num1.length() + num2.length() - 1; int b = Integer.valueOf(String.valueOf(num2.charAt(i))); int c = 0; for(int j = chars1.length - 1; j >= 0; --j){ int a = Integer.valueOf(String.valueOf(num1.charAt(j))); int sum = a * b + c; c = sum / 10; data[i][k - back] = String.valueOf(sum % 10).charAt(0); --k; } if(c != 0){ data[i][k - back] = String.valueOf(c).charAt(0); } ++back; } return addArray(data); } private String addArray(char[][] data) { int c = 0; int row = data.length, col = data[0].length; int k = col; char resChar[] = new char[col + 1]; for(int p = 0; p < col + 1; ++p) { resChar[p] = '0'; } for(int i = col - 1; i >= 0; --i) { int sum = 0; for(int j = 0; j < row; ++j) { sum += Integer.valueOf(String.valueOf(data[j][i])); } sum += c; resChar[k] = String.valueOf(sum % 10).charAt(0); c = sum / 10; --k; } int startIndex = 0, flag = 0; for(int m = 0; m < resChar.length; ++m){ if(resChar[m] != '0'){ startIndex = m; flag = 1; break; } } if(c != 0) { resChar[startIndex - 1] = String.valueOf(c).charAt(0); --startIndex; } if(flag == 0){ return "0"; } return String.valueOf(resChar).substring(startIndex); }
0 0
- Sum—LeetCode-43 Multiply Strings
- LeetCode(43) Multiply Strings
- [leetcode 43] Multiply Strings
- [LeetCode 43]Multiply Strings
- leetcode || 43、Multiply Strings
- leetcode-43 Multiply Strings
- Multiply Strings leetcode 43
- leetcode 43: Multiply Strings
- Leetcode 43 Multiply Strings
- leetcode 43 : Multiply Strings
- Leetcode #43 Multiply Strings
- leetcode 43: Multiply Strings
- LeetCode(43) Multiply Strings
- LeetCode-43 Multiply Strings
- Leetcode#43||Multiply Strings
- [Leetcode]#43 Multiply Strings
- leetcode-43 Multiply Strings
- leetcode 43:Multiply Strings
- Android-drawable
- 寻找单向链表中含有环的入口节点
- move_base导航的源码心得
- java restful api 介绍
- import项目找不到maven 依赖包的处理方法
- Sum—LeetCode-43 Multiply Strings
- 分库实现
- ASP.NET MVC5 + EF6 入门教程 (5) Model和Entity Framework
- jsp自定义标签:body-content取值的含义
- 二叉树的深度优先遍历(DFS)与广度优先遍历(BFS)
- java反射
- Gradle基础学习
- div加超链接
- 5-9 人以群分