您的位置:首页 > 其它

Leetcode之Multiply Strings

2014-09-09 09:34 453 查看
字符串相乘,题目如下:

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.

根据上面的字符串的相乘,变成数组相乘。

C++ Code
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

class Solution

{

public:

string multiply(string s1, string s2)

{

if(s1 == "0" || s2 == "0") return "0";

int len1 = s1.length();

int len2 = s2.length();

int len3 = len1 + len2;

vector<int> num1(len1, 0);

vector<int> num2(len2, 0);

vector<int> num3(len1 + len2, 0);

for(int i = 0; i < len1; i++)

{

num1[i] = s1[i] - '0';

}

for(int i = 0; i < len2; i++)

{

num2[i] = s2[i] - '0';

}

for(int i = 0; i < len1; i++)

{

for(int j = 0; j < len2; j++)

{

num3[i + j + 1] += num1[i] * num2[j];

}

}

string ss = "";

for(int i = len3 - 1; i >= 0; i--)

{

if(i > 0)

{

num3[i - 1] += num3[i] / 10;

}

num3[i] = num3[i] % 10;

ss = char(num3[i] + '0') + ss;

}

ss = ss[0] == '0' ? ss.substr(1) : ss;

return ss;

}

};

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: