ARTS 打卡计划第二周 04/28

ARTS 打卡计划第二周 04/28

Algorithm

Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

example1:

Input: 123
Output: 321

example2:

Input: -123
Output: -321

example3:

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.

package easy;

public class ReverseInteger {

    class Solution {
        public int reverse(int x) {
            int result = 0;
            int com = Integer.MAX_VALUE / 10;
            char[] str = String.valueOf(x).toCharArray();
            char[] newStr = new char[str.length - 1];
            for (int i = str.length - 1; i > 0; i--) {
                newStr[str.length - 1 - i] = str[i];
            }

            try {
                if (newStr.length == 0) {
                    return x;
                }
                //若 start 溢出直接报异常
                int start = Integer.valueOf(String.valueOf(newStr));
                //保证了 ( start * 10 + end ) <= Integer.MAX_VALUE
                if (x >= 0 && start <= com) {
                    int end = Integer.valueOf(String.valueOf(str[0]));
                    if (start < com || (start == com && end <= 7)) {
                        result = start * 10 + end;
                    }
                }

                if (x < 0) {
                    result = -start;
                }
                return result;
            } catch (Exception e) {
                //e.printStackTrace();
                return 0;
            }
        }
    }
}

提交结果

Reverse Integer
Reverse Integer

Review

《Teach Yourself Programming in Ten Years》

  • 沉醉编程
  • 实践中学习
  • 与同行多交流
  • 读计科专业
  • 与同事一起做项目
  • 尝试跟随其他大牛学习
  • 至少学会不同类语言各一种
  • 深入了解计算机组织与结构
  • 语言标准化
  • 良好的意识

Tips

IDEA常用快捷键&使用技巧

Share

排序算法:快速排序 Sorting Algorithms:Quick Sort