LintCode:M-大数相乘
来源:互联网 发布:diy软件 编辑:程序博客网 时间:2024/05/16 18:49
LintCode链接
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
样例
- The length of both num1 and num2 is < 110.
- Both num1 and num2 contains only digits 0-9.
- Both num1 and num2 does not contain any leading zero.
- You must not use any built-in BigInteger library or convert the inputs to integer directly.
public class Solution { /** * @param num1 a non-negative integers * @param num2 a non-negative integers * @return return product of num1 and num2 */ public String multiply(String num1, String num2) { //保证num1长度>num2 if(num1.length()<num2.length()){ return multiply(num2,num1); } int n2 = num2.length(); char[] nums2 = (new StringBuffer(num2)).reverse().toString().toCharArray(); String s1 = singleMul(num1, Integer.valueOf(nums2[0]+""),0); for(int i=1; i<n2; i++){ String s2 = singleMul(num1, Integer.valueOf(nums2[i]+""),i); s1 = sum(s1,s2); } return s1; } String sum(String num1, String num2){ StringBuffer bf = new StringBuffer(""); char[] num1s = (new StringBuffer(num1)).reverse().toString().toCharArray(); char[] num2s = (new StringBuffer(num2)).reverse().toString().toCharArray(); int up=0; int i=0; while(i<num1.length() && i<num2.length()){ int sum = Integer.valueOf(num1s[i]+"")+Integer.valueOf(num2s[i]+"")+up; up = sum/10; bf.append(sum%10+""); i++; } while(i<num1.length()){ int sum = Integer.valueOf(num1s[i]+"")+up; up = sum/10; bf.append(sum%10+""); i++; } while(i<num2.length()){ int sum = Integer.valueOf(num2s[i]+"")+up; up = sum/10; bf.append(sum%10+""); i++; } if(up>0) bf.append(up+""); return bf.reverse().toString(); } //第k位上的数knum与num相乘的结果 String singleMul(String num, int knum, int k){ if(knum==0) return "0"; StringBuffer bf = new StringBuffer(""); char[] chars = new StringBuffer(num).reverse().toString().toCharArray(); int up=0; for(int i=0; i<chars.length; i++){ int mul = (Integer.valueOf(chars[i]+""))*knum+up; up = mul/10; bf.append(mul%10+""); } String res = (up>0?up+"":"")+bf.reverse().toString()+getZeros(k); return res; } String getZeros(int k){ StringBuffer bf = new StringBuffer(""); while(k>0){ bf.append("0"); k--; } return bf.toString(); }}
阅读全文
0 0
- LintCode:M-大数相乘
- 大数相乘
- 大数相乘
- 大数相乘
- 大数相乘
- 大数相乘
- 大数相乘
- 大数相乘
- 大数相乘
- 大数相乘
- 大数相乘
- 大数相乘
- 大数相乘
- 大数相乘
- 大数相乘
- 大数相乘
- 大数相乘
- 大数相乘
- 设计模式-策略模式
- 使用tensorflow保存、加载和使用模型
- 面试题
- Xmind在项目管理中运用
- windows mysql 32位 安装
- LintCode:M-大数相乘
- SpringMvc之数据校验
- 高精度
- 使用Raspi-config配置工具来设置树莓派
- MSSQL如何在原有数据库上新建测试数据库?
- http传输方法
- 码云zheng项目介绍
- android效果之跑马灯
- 架构设计三部曲之如何评审架构设计说明书(转)