Reverse Intege
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
1
2Input: 123
Output: 321Example 2:
1
2Input: -123
Output: -321Example 3:
1
2Input: 120
Output: 21Note:
1
2
3
4Assume 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:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24class 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%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. 预算符优先级:+,-
><<,>>
Add Two Numbers
1 | You are given two non-empty linked lists representing two non-negative |
- Example:
1
2
3Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
代码已经注释的很详细了!
Mycode:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29/**
* 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;
}
};