# leetcode题解日练--2016.8.30

538人阅读 评论(0)

﻿﻿###不给自己任何借口

1、字符串乘法；

2、两个链表加法

——独木舟《深海里的星星Ⅱ》

## 43. Multiply Strings | Difficulty: Medium

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.
tag：数学|字符串

1、题目明确说了不能转整型，可以考虑https://discuss.leetcode.com/topic/30508/easiest-java-solution-with-graph-explanation/2的解法

class Solution {
public:
string multiply(string num1, string num2) {
int m = num1.size(),n=num2.size();
int *pos = new int[m+n]();

for(int i=m-1;i>=0;i--)
{
for(int j=n-1;j>=0;j--)
{
int posHigh = i+j,posLow = i+j+1;
int mul = (num1[i]-'0')*(num2[j]-'0')+pos[posLow];
pos[posHigh] += mul/10;
pos[posLow] = (mul)%10;
}
}

string res="";
for(int i=0;i<m+n;i++)
res =res+char(pos[i]-0+'0');
while(res[0]=='0')
{
res = res.substr(1,res.size()-1);
}
return res.size()==0?"0":res;
}
};

## 2. Add Two Numbers | Difficulty: Medium

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

tag：链表|数学

1、两个链表的长度可能相等也可能不相等，分两种情况讨论：

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if(l1==NULL || l2==NULL) return l1==NULL?l2:l1;
ListNode *res = new ListNode(INT_MIN);
ListNode*cur = res;
int c=0;
while(l1 && l2)
{
cur->next = l2;
int digit = l1->val+l2->val+c;
l2->val = digit%10;
c = digit/10;
cur = cur->next;
l1 = l1->next;
l2 = l2->next;
}
if(l1||l2)
{
if(l1)  cur->next = l1;
cur = cur->next;
while(c&&cur)
{
int digit = (cur->val+c);
cur->val = digit%10;
c = digit/10;
if(cur->next)  cur = cur->next;
else    break;
}
}
if(c)  {cur->next=new ListNode(1);}
return res->next;
}
};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：74813次
• 积分：1428
• 等级：
• 排名：千里之外
• 原创：75篇
• 转载：0篇
• 译文：0篇
• 评论：23条
文章分类
评论排行
最新评论