leetcode@ [2/43] Add Two Numbers / Multiply Strings(大整数运算)
2015-11-17 14:39
429 查看
https://leetcode.com/problems/multiply-strings/
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.
View Code
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.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { vector<int> na; na.clear(); vector<int> nb; nb.clear(); while(l1) { na.push_back(l1->val); l1 = l1->next; } while(l2) { nb.push_back(l2->val); l2 = l2->next; } vector<int> sum(max(na.size(), nb.size()) + 1); for(int i=0;i<sum.size();++i) sum[i] = 0; int i=0; for(;i<min(na.size(), nb.size());++i) sum[i] = na[i] + nb[i]; for(;i<max(na.size(), nb.size());++i) sum[i] = max(na.size(), nb.size())==na.size() ? na[i]: nb[i]; for(int i=0;i<sum.size()-1;++i) { if(sum[i] >= 10) { sum[i+1] += sum[i] / 10; sum[i] = sum[i] % 10; } } if(sum[sum.size()-1] == 0) sum.pop_back(); ListNode *head = new ListNode(-1); ListNode *r = head, *s; for(int i=0;i<sum.size();++i) { s = new ListNode(-1); s->val = sum[i]; r->next = s; r = s; }r->next = NULL; head = head->next; return head; } };
View Code
相关文章推荐
- android屏幕适配
- 16 从EventLoop取消注册和重新注册
- js 语法
- ipcs查看消息队列命令
- iOS 8.0 之后相册授权直接跳转到设置
- data-*的定义和用法
- 如何为ABAP程序添加权限检查
- 制作一个类似登录界面的窗体(无最大最小化栏)
- 11.2 非模态对话框
- ORA-12519: TNS:no appropriate service handler found 解决
- Linux 下Oracle 手工create database 脚本和步骤
- 292 Nim Game
- OC字符串的常规用法NSString的操作
- 在linux下开启FTP服务
- 文件操作
- iOS7默认状态栏文字颜色为黑色,项目需要修
- 怎么事项iMindMap中文字格式的修改
- 1043. Is It a Binary Search Tree (25)
- 15 选择正确的线程模型
- 总结Cnblogs支持的常用Markdown语法