本文共 2998 字,大约阅读时间需要 9 分钟。
通过第一次的题也大概知道了leetcode的写题方式,不用头文件,库文件各种东西它只给你一个函数/方法, 把这个题的解决方法写入这个函数/方法即可,而且支持vim模式下的编辑,真的很方便
Given an array of integers, return indices of the two numbers such that theyadd up to a specific target.You may assume that each input would have exactly one solution, and you maynot use the same element twice.
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
Mycode:
class Solution {public: vector twoSum(vector & nums, int target) { vector ans; int l=nums.size(); bool flag=false; for(int i=0;i
Given a 32-bit signed integer, reverse digits of an integer.
Input: 123Output: 321
Input: -123Output: -321
Input: 120Output: 21
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purposeof this problem, assume that your function returns 0 when the reversedinteger overflows.
Mycode:
class Solution {public: int reverse(int x) { long long ans=0; long long Max = ((long long)1<<31) - 1; long long Min = -(Max+1); if (x==0){ ; } else{ vector v; while(x){ v.push_back(x%10); x /= 10; } for(int i = 0; i < v.size()-1; i++){ ans = (ans + v[i])*10; } ans += v.back(); } if (ans > Max || ans < Min) ans=0; return (int)ans; }};
这道题简单,但是坑点贼多,我WA了好多发,但主要还是自己写程序bug太多了啊。
记录一下心得吧。1.int
范围能撑到1<<30
,1<<31
要用long long
定义.2. 初始化1<<31
这种long long
型数据时,要把1强转为long long
才行,要不然会溢出. 3. 预算符优先级:+,-
><<,>>
You are given two non-empty linked lists representing two non-negativeintegers. The digits are stored in reverse order and each of their nodescontain a single digit. Add the two numbers and return it as a linked list.You may assume the two numbers do not contain any leading zero, except thenumber 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 0 -> 8Explanation: 342 + 465 = 807.
代码已经注释的很详细了!
Mycode:/** * 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 *ans = new ListNode(-1); //创建答案结点 ListNode *p = ans; int carry=0; //记录进位 while(l1 || l2){ //l1,l2链表全部遍历完才退出循环 int x = l1 ? l1->val : 0; int y = l2 ? l2->val : 0; int sum = x + y + carry; carry = sum/10; //更新进位,若有进位,则给下一个l1,l2结点加起来的sum+1 p->next = new ListNode(sum % 10);//更新p的下一个结点 p = p->next; if (l1) l1 = l1->next; if (l2) l2 = l2->next; } //特殊情况处理,若l1,l2等长且最后一个结点相加>9,则再进一次位 if (carry) p->next = new ListNode(1); return ans->next; }};
转载地址:http://defqb.baihongyu.com/