zoukankan      html  css  js  c++  java
  • Add Two Numbers

    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

    struct ListNode {
        int val;
         ListNode *next;
        ListNode(int x) : val(x), next(NULL) {}
    };
    
    /*
        最直白的想法就是将两个字符串翻转, 然后相加,得到的结果再发转
        现在的解法,直接从左到右相加,然后向右进位
    */
    
    class Solution {
    public:
        ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
            
            ListNode* ptr = new ListNode(0);  
            ListNode* head = ptr; 
            int tmp_carry = 0;
            int sum;
    
            while( l1 || l2 )
            {
                 sum = 0;
                 if( l1 )
                 {
                    sum += l1->val;
                    l1 = l1->next;
                 }
    
                 if( l2 )
                 {
                    sum += l2->val;
                    l2 = l2->next;
                 }
            
                 ptr->next = new ListNode( (sum + tmp_carry)%10 );  
                 ptr = ptr->next;
                 tmp_carry = (sum + tmp_carry)/10;
            }
    
            if( tmp_carry )
            {
                 ptr->next = new ListNode( tmp_carry );  
            }
            return head->next;
        }
    };
    当你的才华还撑不起你的野心时,那你就应该静下心来学习。
  • 相关阅读:
    cocos2d-x simpleGame 0
    cocos2d-x 下的HelloWorld
    cocos2d-x windows 配置
    算术入门之加减乘除
    计算摄氏温度
    输出倒三角图案
    厘米换算英尺英寸
    多文件模块的学生信息库系统
    GPS数据处理
    单词长度
  • 原文地址:https://www.cnblogs.com/aceg/p/4423425.html
Copyright © 2011-2022 走看看