ARTS 打卡計劃第二週 04/28

ARTS 打卡計劃第二週 04/28

Algorithm

Reverse Integer

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

example1:

Input: 123
Output: 321java

example2:

Input: -123
Output: -321git

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》app

  • 沉醉編程
  • 實踐中學習
  • 與同行多交流
  • 讀計科專業
  • 與同事一塊兒作項目
  • 嘗試跟隨其餘大牛學習
  • 至少學會不一樣類語言各一種
  • 深刻了解計算機組織與結構
  • 語言標準化
  • 良好的意識

Tips

IDEA經常使用快捷鍵&使用技巧post

Share

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

相關文章
相關標籤/搜索