通过第一次的题也大概知道了leetcode的写题方式,不用头文件,库文件各种东西它只给你一个函数/方法, 把这个题的解决方法写入这个函数/方法即可,而且支持vim模式下的编辑,真的很方便
Mycode:
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> ans; int l=nums.size(); bool flag=false; for(int i=0;i<l-1;i++){ ans.push_back(i); for(int j=i+1;j<l;j++){ if (nums[i]+nums[j]==target){ ans.push_back(j); flag=true; } } if (flag) break; else ans.clear(); } return ans; } };Given a 32-bit signed integer, reverse digits of an integer.
Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: 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 purpose of this problem, assume that your function returns 0 when the reversed integer 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<int> v; while(x){ v.push_back(x); 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. 预算符优先级:+,- > <<,>>
代码已经注释的很详细了! 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; } };