[LeetCode] 012. Integer to Roman (Medium) (C ++/Java/Python), leetcodepython
Index: [LeetCode] Leetcode index (C ++/Java/Python/SQL)
Github: https://github.com/illuz/leetcode
012. Integer_to_Roman (Medium)
Link:
Title: https://oj.leetcode.com/problems/integer-to-roman/
Code (github): https://github.com/illuz/leetcode
Question:
Convert the decimal to the number of Rome.
Analysis:
Simulate it.
"The Basic symbols of the Roman numerals include I (representing the decimal number 1), V (representing 5), X (representing 10), L (representing 50), C (representing 100 ), D (500), M (1000 )." -Rome numeric system (Baidu encyclopedia)
Code:
C ++:
class Solution {private:int val[13] = {1000, 900, 500, 400,100, 90, 50, 40,10, 9, 5, 4,1};string syb[13] = {"M", "CM", "D", "CD","C", "XC", "L", "XL","X", "IX", "V", "IV","I"};public:string intToRoman(int num) {string roman;int i = 0, k;while (num > 0) {k = num / val[i];while (k--) {roman += syb[i];num -= val[i];}i++;}return roman;}};
Java:
public class Solution { private int[] val = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; private String[] syb = new String[] { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; public String intToRoman(int num) { StringBuilder roman = new StringBuilder(); int i = 0, k; while (num > 0) { k = num / val[i]; while (k-- > 0) { roman.append(syb[i]); num -= val[i]; } i++; } return roman.toString(); }}
Python:
class Solution: # @return a string def intToRoman(self, num): val = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ] syb = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" ] roman = '' i = 0 while num > 0: for _ in range(num // val[i]): roman += syb[i] num -= val[i] i += 1 return roman