Algorithm
Reverse Integer,难度是esay。
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:
[−231, 231 − 1]. For the purpose of this
problem, assume that your function returns 0 when the reversed
integer overflows. - 整数颠倒,颠倒算法还是比较简单,对10取模得到最后一位的数组,对10取余得到除个位以后的数字,然后通过循环可以实现将整数颠倒。比较麻烦或者是需要特殊处理的是颠倒以后的整数范围要在 [−231, 231 − 1],也就是int32。(我的思路和网站中的结题思路一致,也可以看网站上的介绍)。
int absx = x;
int result = 0;
if (x > Int32.MaxValue || x < Int32.MinValue)
{
return result;
}
for (int i=0;i<10;i++)
{
if (i > 0)
{
if ((result > 100000000 && result > (Int32.MaxValue / 10)) || (result < -100000000 && result < (Int32.MinValue / 10)))
{
result = 0;
break;
}
result *= 10;
}
if ((result > 100000000 && (absx % 10) > (Int32.MaxValue- result)) || (result < -100000000 && (absx % 10) < (Int32.MinValue - result)))
{
result = 0;
break;
}
result += absx % 10;
absx = absx / 10;
if (absx == 0)
{
break;
}
}
return result;
- 官网的C++版本很简洁也记录下。
class Solution {
public:
int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0;
if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
};
- 判断越界:当颠倒的数据还差一位越界的时候需要进行判断,如果X10以后已经越界就不需要再继续,如果X10以后没有越界,就需要考虑X10以后和剩下部分的结果相加是否超过边界。
- 和 String to Integer (atoi) 这个题目有点像。
Review
最近看了一个视频:VSCode In The Cloud - Setup a Remote Dev Environment
视频连接:https://www.youtube.com/watch?v=9Emn2YQNDl0&t=366s , 官网: https://coder.com/,github: https://github.com/codercom/code-server
网站上的教程是在云端搭建了 vscode 工具,看着很酷,我自己在本地 linux 系统上搭建。启动的时候出错了,有个库有版本太低,还没解决,解决了再来补充。对于长期使用 vscode 编程的人来说可以尝试下。
Tips & Share
这周看的东西比较杂,还是要详细制定好每天的计划,现在上 leetcode 刷题已经养成习惯了,其他的要继续努力。
一直在使用阿里云的产品,前段时间因为个人原因注册和试用亚马逊的ES2,从我个人的角度对比下云产品使用的区别。
- 阿里云,收费方式按照实例数量,实例的费用是按照选择的配置,收费的方式是多种,默认是按天或者包年。
- 亚马逊,收费方式默认按照实例的使用时间,具体的费用也是按照选择实例的配置,把实例关了就不收费,这点和阿里的包年包月不太一样。
- 阿里云会给你一个不变的外网IP,亚马逊默认也会给一个外网IP,但是关闭实例以后再重启外网IP就变了,我也没研究能固定,应该是可以的吧,这也是很一般的需求。
- 还有的区别就是远程登录稍微有点不一样,具体我没操作,感觉还是自制力不够啊,荒废时间。