ARTS打卡:第十四周

ARTS打卡:第十四周

每周完成一个ARTS:

  1. Algorithm:每周至少做一个 leetcode 的算法题
  2. Review:阅读并点评至少一篇英文技术文章
  3. Tip:学习至少一个技术技巧
  4. Share:分享一篇有观点和思考的技术文章

Algorithm

7. Reverse Integer(Easy)

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.

大致题意

给定一个32位的带符号的整数,求翻转之后的整数。

代码实现

解题思路在代码注释,看注释就行了,这题虽然难度是 easy ,但我也是看讨论区才恍然大悟的,人与人之间的差距,一下子就显现出来了(:зゝ∠)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public int reverse(int x) {
int result = 0;
while (x != 0) {
//求整数的尾部数字,比如 123,那么当前的尾数是 3
int tail = x % 10;
// 逐位数字进行翻转,比如 123,先翻转一位是 3,继续翻转则是 3*10 + 2,以此类推
int newResult = result * 10 + tail;
// 如果 result * 10 + tail 发生溢出,溢出值 newResult/10 是不等于 result 的,这里不减去尾部值 tail,是因为值为整形,除于10后,小数点会被移除。
if (newResult / 10 != result) {
return 0;
}
// 没有溢出则继续遍历
x /= 10;
result = newResult;
}
return result;
}

运行结果&复杂度分析

运行结果:
Runtime: 1 ms, faster than 100.00% of Java online submissions for Reverse Integer.
Memory Usage: 33.6 MB, less than 9.08% of Java online submissions for Reverse Integer.

时间复杂度:O(logx)
空间复杂度:O(1)

Review

本周阅读:《How to write code you will love in the future》

作者在文中根据自己多年的行业经验,提出了几点建议,并结合自身的经历,对之一一说明。

  1. Never compromise on code quality(从不对代码质量妥协)
  2. Always document and write code comments(总是编写文档和代码注释)
  3. Don’t reinvent the wheel, unless you ensure it is maintainable(不要重复造轮子,除非你能确保它是可维护的)
  4. Always test your codebase(总是测试你的代码库)
  5. Keep learning(保持学习)

Tip

最近学到什么新技巧(:зゝ∠),就随意分享个 windows 10 多窗口和多桌面的快捷键吧。

多桌面快捷键
win + tab:打开多桌面视图
ctrl + win + ← 或 ctrl + win + →:快速左右切换虚拟桌面

多窗口快捷键
win + ↑:上分屏
win + ↓:下分屏
win + ←:左分屏
win + →:右分屏

Share

本周分享: