leetcode_Multiply Strings
来源:互联网 发布:华为因数据丢失事件 编辑:程序博客网 时间:2024/05/21 09:19
描述:
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.
思路:
简而言之,要实现的就是BigInteger(a).Multiply(BigInteger(b))的功能,但很显然,leetcode中不让用BigInteger
代码:
public class Solution { public String multiply(String num1, String num2){if(num1==null||num2==null)return new String();num1=num1.trim();num2=num2.trim();if(num1.equals("0")||num2.equals("0"))return "0"; List<Integer>listNum1=new ArrayList<>(); List<Integer>listNum2=new ArrayList<>(); List<Integer>listResult=new ArrayList<>(); int len1=num1.length(); int len2=num2.length(); int i=0,j=0,lenResult=0,index=0; int baseNum=0,flowNum=0,tempNum1=0,tempNum2=0; for( i=len1-1;i>=0;i--) listNum1.add(num1.charAt(i)-'0'); for( i=len2-1;i>=0;i--) listNum2.add(num2.charAt(i)-'0'); tempNum2=listNum2.get(0); for(i=0;i<len1;i++) { tempNum1=listNum1.get(i); tempNum1=tempNum1*tempNum2+flowNum; baseNum=tempNum1%10; flowNum=tempNum1/10; listResult.add(baseNum); } if(flowNum!=0) { listResult.add(flowNum); flowNum=0; } for(j=1;j<len2;j++) { baseNum=0;flowNum=0; tempNum2=listNum2.get(j); lenResult=listResult.size(); for(i=0;i<len1;i++) { index=i+j; if(index<lenResult) { tempNum1=listNum1.get(i); tempNum1=tempNum1*tempNum2+flowNum+listResult.get(index); baseNum=tempNum1%10; flowNum=tempNum1/10; listResult.set(index, baseNum); } else { tempNum1=listNum1.get(i); tempNum1=tempNum1*tempNum2+flowNum; baseNum=tempNum1%10; flowNum=tempNum1/10; listResult.add(baseNum); } } if(flowNum!=0) { listResult.add(flowNum); flowNum=0; } } if(flowNum!=0) listResult.add(flowNum); StringBuilder sBuilder=new StringBuilder(); for(int num:listResult) sBuilder.append(num); sBuilder.reverse(); return sBuilder.toString(); }}
0 0
- leetcode_Multiply Strings
- Leetcode_multiply-strings (updated c++ and python version)
- leetCode_Multiply Strings(大位数相乘)
- Strings
- Strings
- strings
- Strings
- Strings
- Strings
- strings
- Strings
- Foundation - strings
- Localizable.strings
- C++ Strings
- strings.cpp
- strings.h
- C++ Strings
- Splitting strings
- 问题解决 —— Http Status 500
- 关于 UNITY3D接入 SHARE SDK 安卓微信部分(不跳审核)的注意点!
- 卓有成效的敏捷开发流程
- 业务流程图的绘制流程分享
- 软件功能测试Checklist 在 Web 测试中的重要性
- leetcode_Multiply Strings
- UML类图与类的关系详解
- perl the special operator
- qemu for windows编译
- 素数判断+DFS POJ2034
- 在Linux下安装JITwatch
- Nginx 反向代理、负载均衡、页面缓存、URL重写及读写分离详解
- 黑马程序员——java的IO之File类
- java 异常java.lang.UnsupportedOperationException