|
| 1 | +// |
| 2 | +// 43multiplyStrings.cpp |
| 3 | +// leecode |
| 4 | +// |
| 5 | +// Created by lixiangqian on 16/10/24. |
| 6 | +// Copyright © 2016年 lixiangqian. All rights reserved. |
| 7 | +// |
| 8 | + |
| 9 | +#include <iostream> |
| 10 | +#include <stdio.h> |
| 11 | +#include <string> |
| 12 | +#include <vector> |
| 13 | +#include <algorithm> |
| 14 | +#include <map> |
| 15 | +#include <set> |
| 16 | +#include <math.h> |
| 17 | +#include <stdlib.h> |
| 18 | +using namespace std; |
| 19 | +int * stringToNumberList(string a, long al); |
| 20 | +string multiplyStrings(string num1, string num2){ |
| 21 | + string r; |
| 22 | + if(num1=="0"||num2=="0") |
| 23 | + return "0"; |
| 24 | + long al = num1.size(); |
| 25 | + long bl = num2.size(); |
| 26 | + int * rr = new int[al+bl+1]; |
| 27 | + memset(rr, 0, (al+bl+1)*4); |
| 28 | + |
| 29 | + int * aa = stringToNumberList(num1, al); |
| 30 | + int * bb = stringToNumberList(num2, bl); |
| 31 | + for(int i=0;i<bl;i++){ |
| 32 | + int *temp= new int[al+1]; |
| 33 | + memset(temp, 0, (al+1)*4); |
| 34 | + int add = 0; |
| 35 | + for (int j=0; j < al; j++){ |
| 36 | + *(temp+j) = (*(aa+j) * *(bb+i) + add)%10; |
| 37 | + add = ((*(aa+j)) * (*(bb+i)) +add)/10; |
| 38 | + } |
| 39 | + *(temp+al)=add; |
| 40 | + for(int xx=0;xx<al+1;xx++){ |
| 41 | + cout<<*(temp+xx)<<endl; |
| 42 | + } |
| 43 | + add=0; |
| 44 | + for(int j=0; j<=al;j++){ |
| 45 | + int temprr = *(rr+i+j); |
| 46 | + *(rr+i+j) = (temprr+ *(temp+j)+add)%10; |
| 47 | + add = (temprr+ (*(temp+j))+add)/10; |
| 48 | + } |
| 49 | + if(add>0){ |
| 50 | + *(rr+i+al+1) = add; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + for(long k=al+bl-2; k>=0 ;k--){ |
| 55 | + r +=to_string(*(rr+k)); |
| 56 | + } |
| 57 | + if(*(rr+al+bl-1)>0 && *(rr+al+bl-1)<10){ |
| 58 | + r =to_string(*(rr+al+bl-1))+r; |
| 59 | + } |
| 60 | + return r; |
| 61 | +} |
| 62 | +int * stringToNumberList(string a, long al){ |
| 63 | + int *aa = new int[al]; |
| 64 | + for(int i=0;i<al;i++){ |
| 65 | + *(aa+i)=a[al-i-1]-'0'; |
| 66 | + } |
| 67 | + return aa; |
| 68 | +} |
| 69 | +int main(){ |
| 70 | + string a = "12345"; |
| 71 | + string b = "31"; |
| 72 | + string result = multiplyStrings(a,b); |
| 73 | + cout<<"helloworld"<<endl; |
| 74 | + cout<<result<<endl; |
| 75 | +} |
0 commit comments