LeetCode #7. Reverse Integer プログラミング練習

問題:

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.

難易度: easy
入力: Int
目的: 入力された整数の反対数字を出力せよ
出力: Int
注意: 入力は32-bitの整数

難易度easyの問題です。
入力が321なら下から読んだ123を出力、入力が-123456なら-654321を出力。
非常に簡単な問題ですが、こう言った問題、ミスなく素早く書けるかが要です。
実は私、日本企業のコーディングテストで二、三回こう言った類の問題に会っています。
実際はもう少し複雑な問題でしたが、これを素早く解ければ問題なく解けるレベルです。

注意すべき事: 

  • マイナスの数字が入力された場合
  • Integer の範囲が-2^31 ~ 2^31-1までなので、-2^31が入力される場合処理によってはオーバーフローします。
  • 処理の途中でオーバーフローした場合は問題文のNoteに書いてある通り0を返しましょう。


以下回答です。

class Solution {
    public int reverse(int x) {
        int temp = 0;
        if(x < 0){
            temp = -x;
        }
        else{
            temp = x;
        }
        if( temp == 0 ){
            return temp;
        }
        int res = 0;
        int result = 0;
        while(temp != 0){
            if( result>(Integer.MAX_VALUE-temp%10)/10 )
                return 0;
            res = temp % 10;
            result = result*10 + res;
            temp /= 10;
        }
        if(x < 0){
            result = - result; 
        }
        return result;
    }

入力がマイナスプラスに関わらずプラスとして処理をし、マイナスであれば最後に反転する処理をしています。
入力を%10で下の数字から取り出しresult*10で一文字ずつ格納していきます。
元の数字は毎回/10で回していき0になったらbreakします。
Time ComplexityはO(n)です。

ではでは