1.21 Reverse Integer

Description

Reverse digits of an integer.

Example1: x = 123, return 321 Example2: x = -123, return -321

Method

Math method : the issue is that when we reverse the interger we should care about the overflow . So we use a check sentence in recursive reverse since if we add a value that is overflow, it will changed to a random value, so it cannot be used to back to origianl value by undo last step

Time and Space Complexity

time : o(n) space : o(1)

Code

public class Solution {

  public int reverse(int x) {

    int res = 0;

    while (x != 0){
          int tail = x % 10;
          int newres = res * 10 + tail;
          if ((newres - tail) / 10 != res){
              return 0;
          } // since if the newres overflow, it will change the value of res * 10 + tail so we undo it it will not equal to res 
          res = newres;
          x /= 10;
    }
    return res;
}

}

results matching ""

    No results matching ""