My best Swift-solution (sorry for English)


  • 0
    S
        1. the only condition for the overflow: currentReversedValue > Int32.max/10 and we have one more digit for reversing - there is garanteed overflow (with considering p.2)
        2. the very last digit for reversing in the correct border case can be only 1 or 2, and it can not be a couse of the overflow, it always smaller then 7 for positive and 8 for negative
        3. as result of p.2 we can process absolute value, and consider sign only at the end
        4. we can use true Int32 as parameter and result of the function, and as type for 'reversed', and it will work correctly (only update type castings)
    
    class Solution {
        func reverse(_ x: Int) -> Int {
            var value: Int = abs(x)
            var reversed: Int = 0
            let border = Int32.max / 10
            while value != 0 {
                if reversed > border {
                    return 0
                }
                reversed = reversed * 10 + value % 10
                value /= 10
            }
            
            return x > 0 ? reversed : -reversed
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.