Scaffolded code is wrong for Swift


  • 0
    A

    The provided code has signature (Int) -> Int. In Swift, Int has a system-dependant type. This question deals specifically with 32 bit math, so the Int32 type should be used instead.

    Otherwise, you end up having to do needless conversion instead:

    class Solution {
    	func reverse(_ x: Int) -> Int {
    		var x = Int32(x)
    		var result: Int32 = 0
    		while x != 0 {
    			let digit = x % 10
    
    			let (r1, didOverflow1) = Int32.multiplyWithOverflow(result, 10)
    			guard !didOverflow1 else { return 0 }
    			let (r2, didOverflow2) = Int32.addWithOverflow(r1, digit)
    			guard !didOverflow2 else { return 0 }
    
    			result = r2
    			x /= 10
    		}
    		return Int(result)
    	}
    }

Log in to reply
 

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