LeetCode - Algorithms
  • Introduction
  • 1. Two Sum
  • 2. Add Two Numbers
  • 3. Longest Substring Without Repeating Characters
  • 4. Median of Two Sorted Arrays
  • 5. Longest Palindromic Substring
  • 6. ZigZag Conversion
  • 7. Reverse Integer
  • 8. String to Integer (atoi)
  • 9. Palindrome Number
  • 10. Regular Expression Matching
  • 11. Container with Most Water
  • 12. Integer to Roman
  • 13. Roman to Integer
  • 14. Longest Common Prefix
  • 15. 3Sum
  • 16. 3Sum Closest
  • 17. Letter Combinations of a Phone Number
  • 18. 4Sum
  • 19. Remove Nth Node From End of List
  • 20. Valid Parentheses
  • 21. Merge Two Sorted Lists
  • 22. Generate Parentheses
  • 23. Merge k Sorted Lists
  • 24. Swap Nodes in Pairs
  • 25. Reverse Nodes in k-Group
  • 26. Remove Duplicates from Sorted Array
  • 27. Remove Element
  • 28. Implement strStr()
  • 29. Divide Two Integers
  • 30. Substring with Concatenation of All Words
  • 31. Next Permutation
  • 32. Longest Valid Parentheses
  • 33. Search in Rotated Sorted Array
  • 34. Search for a Range
  • 35. Search Insert Position
  • 36. Valid Sudoku
  • 37. Sudoku Solver
  • 38. Count and Say
  • 39. Combination Sum
Powered by GitBook
On this page
  • Problem
  • Analysis
  • Code

12. Integer to Roman

Problem

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

Related Topics:

Math String

Analysis

方法一:打表,然后按位,对应进行转化。

方法二:相邻的重复字符,具有重复叠加的含义。打表记录下特殊的字符后,便可以通过相减,推出重复字符出现的次数,从而得到结果。

Code

简单打表

class Solution {

    private val i = arrayOf("", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX")
    private val x = arrayOf("", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC")
    private val c = arrayOf("", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM")
    private val m = arrayOf("", "M", "MM", "MMM")

    fun intToRoman(num: Int): String {

        return m[num / 1000] + c[(num % 1000) / 100] + x[(num % 100) / 10] + i[num % 10]
    }
}

相减取值

class Solution {

    private val i = arrayOf(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
    private val r = arrayOf("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")

    fun intToRoman(num: Int): String {

        val string = StringBuilder()

        var index = 0
        var n = num
        while (n > 0) {
            while (n >= i[index]) {
                n -= i[index]
                string.append(r[index])
            }
            index++
        }

        return string.toString()
    }
}
Previous11. Container with Most WaterNext13. Roman to Integer

Last updated 6 years ago