題目
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one’s added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
-
I can be placed before V (5) and X (10) to make 4 and 9.
-
X can be placed before L (50) and C (100) to make 40 and 90.
-
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
Example 1:
Input: “III”
Output: 3
Example 2:
Input: “IV”
Output: 4
Example 3:
Input: “IX”
Output: 9
Example 4:
Input: “LVIII”
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:
Input: “MCMXCIV”
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
翻譯
Palindrome 迴文,亦稱回文、回環,是正讀反讀都能讀通的句子。
也就是說給你一串數字,檢查是否為回文,比如給你 12321、11、22 都是回文,
但是個位數字就不是回文了。
額外條件問你能不能不用轉成字串的方法反轉完成。
思維
這個題目超級長,可能需要花一點時間理解,簡單來說,就是設定7個羅馬數字,分別代表不同的數字,比如說 I 就代表1,然後這邊規則就是,如果前一個羅馬數字比後面羅馬數字大,則回傳前一個羅馬數字,反之,則大減小,最終把結果回傳。
實作
這樣一開始就先宣告好有限的集合,我們就用 Map 來表示,為了方便閱讀,我們先對輸入的字串進行數值的轉換,透過 map 來將字串轉換成數字陣列,接著對這個陣列兩兩判斷,一開始我們會宣告一個變數來儲存最終結果,由於最後會算到陣列的前一個數字,避免最後一個數字沒有比對的對象,所以會先把最後一個數字加到結果內。
舉個例子來說好了,MCMXCIV 換成陣列就是,
[1000, 100, 1000, 10, 100, 1, 5]
兩兩相比就會變成
[大], [小大], [小大],[小大]
小大的部分是後減前,而大的部分是直接大加上去
,這樣一來就會找到一個規則,只要兩數相比,左邊比右邊大或等於,
總和直接加上左邊的值,如果左邊等於右邊小,則總和扣除掉右邊即可。
fun romanToInt(s: String): Int {
val map = mapOf("I" to 1, "V" to 5, "X" to 10, "L" to 50, "C" to 100, "D" to 500, "M" to 1000)
val list = s.map {
map[it.toString()] ?: 0
}
var sum = list.last()
list.forEachIndexed { index, _ ->
if(index < list.size - 1) {
if (list[index] < list[index + 1]) sum -= list[index]
else sum += list[index]
}
}
return sum
}