zoukankan      html  css  js  c++  java
  • 链式A+B

    题目描述
    有两个用链表表示的整数,每个结点包含一个数位。这些数位是反向存放的,也就是个位排在链表的首部。编写函数对这两个整数求和,并用链表形式返回结果。

    给定两个链表ListNode* A,ListNode* B,请返回A+B的结果(ListNode*)。

    测试样例:
    {1,2,3},{3,2,1}
    返回:{4,4,4}

    solution:

    # -*- coding:utf-8 -*-
    class ListNode:
        def __init__(self, x):
            self.val = x
            self.next = None
    
    
    class Plus:
        def plusAB(self, a, b):
            carry = 0
            pre = ListNode(0)
            work = pre
            while a and b:
                temp = a.val + b.val + carry
                if temp>9:
                    temp -= 10
                    carry = 1
                else:
                    carry = 0
                new = ListNode(temp)
                work.next = new
                work = work.next
                a = a.next
                b = b.next
            while a:
                temp = a.val + carry
                if temp>9:
                    temp -= 10
                    carry = 1
                else:
                    carry = 0
                new = ListNode(temp)
                work.next = new
                work = work.next
                a = a.next
            while b:
                temp = b.val + carry
                if temp>9:
                    temp -= 10
                    carry = 1
                else:
                    carry = 0
                new = ListNode(temp)
                work.next = new
                work = work.next
                b = b.next
            if carry==1:
                new = ListNode(1)
                work.next = new
            return pre.next
    
  • 相关阅读:
    tiptop之4gl调试3/31
    打印空白3/31
    佛陀教育入门
    什么是佛教
    智、觉
    保持头脑清醒的窍门2/13
    php中将数组转换为指定符号分割的字符串
    kali下apche配置多网站
    php数组指定字段排序
    php 语句块耗时性能测试
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/11182391.html
Copyright © 2011-2022 走看看