簡體   English   中英

羅馬數字檢查器(接受輸入並檢查是否是有效的羅馬數字)(Java)

[英]Roman Numeral Checker (takes input and checks if a valid roman numeral)(Java)

我想請一些幫助,如果你們想出了我聯盟中的一些奇思妙想,請解釋一下。

我確信用一個巨大的 IF 或一個 SWITCH 我可以做到這一點,但必須有更優化的方法。 我正在考慮分配值,然后制定一個算法來檢查所有情況。

或者可能只是將第一個元素與其后面的元素進行比較,如果第一個元素小於第二個元素,則減去,否則添加。

我確實計划使用數組

供你參考。

米 1000

D 500

100

升 50

X 10

5

我 1

使用地圖,存儲所有可能的值,然后查找它們:

Map lookup = new LinkedHashMap<Integer, String>();

lookup.put(10, "X");
lookup.put(11, "XI);
// and so on

Integer year = lookup.get("MMXIV");
System.out.println(year); //prints 2014

您可以將所有值放在一個文件中並對其進行解析以填充您的地圖。

 const map = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000, }; function isValidRoman(roman) { const length = roman.length; let exceptions = 0; let min = map[roman[0]]; for (let i = 1; i < length; i++) { const value = map[roman[i]]; if (value > min) { const isExceptionValid = checkIsExceptionValid(value, min); if (!isExceptionValid) return false; else { exceptions++; if (exceptions === 2) return false; } } } return true; } function checkIsExceptionValid(value, min) { if (min === 1) return [5, 10].includes(value); else if (min === 10) return [50, 100].includes(value); else if (min === 100) return [500, 1000].includes(value); return false; } const testCases = [ "IXC", "CDM", "IXV", "I", "X", "L", "MMDCL", "IL", "XM", "VX", "MCMLXXXVII", ]; const expected = [ false, false, false, true, true, true, true, false, false, false, true, ]; testCases.forEach((testcase, index) => { console.log( "result for testcase = ", testcase, " = ", isValidRoman(testcase), ",expected = ", expected[index] ); });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM