Simple & readable Swift solution


  • 0
    R
    let I = "I" // 1
    let V = "V" // 5
    let X = "X" // 10
    let L = "L" // 50
    let C = "C" // 100
    let D = "D" // 500
    let M = "M" // 1000
    
    
    func intToRoman(_ num: Int) -> String {
      var num = num
      var string = ""
    
      // List of full dividers
      let full = [1000, 500, 100, 50, 10, 5]
      let fullStr = [M, D, C, L, X, V]
      // List of possible remainders that can be encoded in subtractive notation
      let nFull = [900, 400, 90, 40, 9, 4]
      let nFullStr = [C+M, C+D, X+C, X+L, I+X, I+V]
    
      for (idx, rmndr) in nFull.enumerated() {
        // Get divider
        let dvdr = full[idx]
        // Try to divide and append a string
        if num / dvdr > 0 {
          string += String(repeating: fullStr[idx], count: num / dvdr)
          num = num % dvdr
        }
    
        // Check, if the remainder can be encoded using subtractive notation
        if num >= rmndr {
          string += nFullStr[idx]
          num -= rmndr
        }
      }
    
      // The remainder is amount of Is to add
      string += String(repeating: I, count: num)
    
      return string
    }
    

Log in to reply
 

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