Swift solution


  • 0
    H
    static func reverseInt(_ x: Int32) -> Int32 {
            var input = x
            var result: Int32 = 0
            repeat {
                if Int32.max / 10 < result {
                    return 0
                }
                if Int32.min / 10 > result {
                    return 0
                }
                result = result * 10 + input % 10
                input = input / 10
            } while input != 0
    
            return result
        }
    

    Test Cases:

    func testReverseInt() {
            let result = LeetCode.reverseInt(123)
            XCTAssertTrue(result == 321, "result: \(result)")
    
            let result2 = LeetCode.reverseInt(-123)
            XCTAssertTrue(result2 == -321, "result: \(result2)")
    
            let result3 = LeetCode.reverseInt(150)
            XCTAssertTrue(result3 == 51, "result: \(result3)")
    
            let result4 = LeetCode.reverseInt(2147483647)
            XCTAssertTrue(result4 == 0, "result: \(result4)")
    
            let result5 = LeetCode.reverseInt(-2147483648)
            XCTAssertTrue(result5 == 0, "result: \(result5)")
    
            let result6 = LeetCode.reverseInt(2147447412)
            XCTAssertTrue(result6 == 2147447412, "result: \(result6)")
    
            let result7 = LeetCode.reverseInt(-2147447412)
            XCTAssertTrue(result7 == -2147447412, "result: \(result7)")
        }
    

Log in to reply
 

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