LeetCode [1--sum of two numbers] LeetCode [2--addition of two numbers]

Sum of two numbers

Title description

Given an integer array nums and a target value target, please find the two integers whose sum is the target value in the array, and return their array index.
You can assume that each input will only correspond to one answer. However, you cannot reuse the same elements in this array.
Insert picture description here

Problem-solving ideas

Direct double loop traversal, no brain

Code

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int>res;
        for(int i = 0; i<nums.size();++i)
        {
            for(int j = i+1;j<nums.size();++j)
            {
                if(nums[i]+nums[j] == target)
                {
                    res.push_back(i);
                    res.push_back(j);
                }
            }
        }
        return res;
    }
};

Add two numbers

Title description

Two non-empty linked lists are given to represent two non-negative integers . Among them, their respective digits are stored in reverse order , and each of their nodes can only store one digit .
If we add these two numbers together, a new linked list will be returned to represent their sum.
You can assume that except for the number 0, neither of these numbers will start with 0.
Insert picture description here

Problem-solving ideas

The output result is the reverse order of the linked list, so you only need to add the numbers on each bit of the two linked lists as a node of the new linked list and hang the chain continuously.

Code

/**
 * 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) {
        ListNode* newHead = new ListNode(-1); //新链表
        ListNode* Cur = newHead;
        int sum = 0; //每一位上面的和
        bool carry = false; //进位标志
        while(l1!=NULL || l2!=NULL)
        {
            sum = 0;
            if(l1!=NULL)
            {
                sum+=l1->val;
                l1=l1->next;
            }
            if(l2!=NULL)
            {
                sum+=l2->val;
                l2= l2->next;
            }
            if(carry)
            {
                sum+=1;
            }
            Cur -> next = new ListNode(sum%10);
            carry = sum>=10? true:false;
            Cur = Cur->next;
            
        }
        if(carry)
        {
            Cur->next = new ListNode(1);
        }
        //没有头节点,返回头结点的下一个结点
        return newHead->next;
    }
};
Published 253 original articles · praised 41 · 40,000+ views

Guess you like

Origin blog.csdn.net/liuyuchen282828/article/details/104522213