Leetcode117: Add Two Numbers
来源:互联网 发布:java 线程同步锁 编辑:程序博客网 时间:2024/05/01 22:43
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
/** * 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) { int flag=0; ListNode* p = new ListNode(0); ListNode* tmp = p; while(l1 || l2) { int val1 = 0; if(l1) { val1 = l1->val; l1 = l1->next; } int val2 = 0; if(l2) { val2 = l2->val; l2 = l2->next; } int sum = val1 + val2 + flag; tmp->next = new ListNode(sum%10); flag = sum/10; tmp = tmp->next; } if(flag == 1) tmp->next = new ListNode(1); return p->next; }};
python代码:
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ l3 = ListNode(-1) head = l3 flag = 0 sum = 0 while l1!=None and l2!=None: sum = l1.val + l2.val + flag flag = sum/10 sum %= 10 head.next = ListNode(sum) head = head.next l1 = l1.next l2 = l2.next while l1!=None: sum = l1.val + flag flag = sum / 10 sum %= 10 head.next = ListNode(sum) head = head.next l1 = l1.next while l2!=None: sum = l2.val + flag flag = sum / 10 sum %= 10 head.next = new ListNode(sum) head = head.next l2 = l2.next if flag: head.next = ListNode(flag) return l3.next
0 0
- Leetcode117: Add Two Numbers
- Add two numbers & Add binary
- LeetCode: Add Two Numbers
- Add Two Numbers
- LeetCode: Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode Add Two Numbers
- Leetcode: Add Two Numbers
- Add Two Numbers
- LeetCode : Add Two Numbers
- LeetCode Add Two Numbers
- [LeetCode] Add Two Numbers
- LeetCode4: Add Two Numbers
- Leetcode : Add Two Numbers
- Add Two Numbers
- 【leetcode】Add Two Numbers
- add two numbers
- Add Two Numbers
- ZOJ 3228 Searching the String(AC自动机)
- UML——用例图
- 关于iOS开发的各种证书
- Activity组件启动过程
- C#加密算法汇总(推荐)
- Leetcode117: Add Two Numbers
- SPServer : 一个基于线程池(包括HAHS和LF)的高并发 server 框架
- tomcat配置HTTPS方式
- Python repr() 或str() 函数
- 移动开发博客汇总
- epoll在ET和LT模式下读写
- xUtils
- 移动视频直播点播方案
- Xcode中的iOS模拟器(iOS Simulator)的介绍和使用心得