leetcode 43. Multiply Strings
2016-07-14 10:58
316 查看
//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. //Converting the input string to integer is NOT allowed. //You should NOT use internal library such as BigInteger. public class Solution { public static String multiply(String num1, String num2) { int number1; int number2; int carry = 0; //进位 int temp = 0; //剩余值 int[] result = new int[num1.length()+num2.length()]; StringBuilder sb = new StringBuilder(); //返回相乘结果的字符串 for(int i = num1.length()-1;i>=0;i--){ //逐位相乘再保存 number1 = num1.charAt(i)-'0'; for(int j = num2.length()-1;j>=0;j--){ number2 = num2.charAt(j)-'0'; result[i+j+1] = result[i+j+1]+number1*number2; } } for(int i = result.length-1;i>=0;i--){ //对结果进行进位或求余 temp = (result[i]+carry)%10; carry = (result[i]+carry)/10; result[i] = temp; } for(int i = 0;i<result.length;i++){ //将结果加入字符串中 sb.append(result[i]); } while(sb.length()>1 && sb.charAt(0) == '0'){ //删除结果中左边的0,只有一个0时则不删除 sb.deleteCharAt(0); } return sb.toString(); } public static void main(String[] args) { // TODO Auto-generated method stub String result = multiply("8","7"); System.out.println(result); } }
相关文章推荐
- PAT 团体程序设计天梯赛-练习集 L1-023. 输出GPLT
- Factroy 简单工厂
- 浅谈OCR之Tesseract
- fgets代替gets
- YUV视频格式到RGB32格式转换的速度优化 上篇
- java 计算时间差(显示形式 :如1天2小时30分钟 )
- Android Handler内部类+WeakReference
- hdu 1213 并查集模板
- 【刷题之路】包含min函数的栈
- 安卓输入框加入清除按钮
- 一台机器运行多个JBoss多实例
- CodeForces 688A-Opponents
- sqlplus运行sql文件
- Hibernate @Transient
- js 怎么获得写在css文件中的display属性
- 无聊解一道数学题:喝农药杀人(这什么题目!!??)
- boostrap datetimepicker问题
- mongodb分片
- 在 ASP.NET MVC 项目中使用 WebForm
- 网易视频云:HBase最佳实践-列族设计优化