[英]Java to Mips with two arrays
我對MIPS完全陌生,但是我正在嘗試轉換我的java程序,該程序從用戶那里獲取羅馬數字形式的輸入,並將其轉換為整數,然后將其打印出來。 這是我的Java程序:
private static int decodeSingle(char letter) {
switch(letter) {
case 'M': return 1000;
case 'D': return 500;
case 'C': return 100;
case 'L': return 50;
case 'X': return 10;
case 'V': return 5;
case 'I': return 1;
default: return 0;
}
}
public static int decode(String roman) {
int result = 0;
String uRoman = roman.toUpperCase(); //case-insensitive
for(int i = 0; i < uRoman.length() - 1; i++) {//loop over all but the last character
//if this character has a lower value than the next character
if (decodeSingle(uRoman.charAt(i)) < decodeSingle(uRoman.charAt(i + 1))) {
//subtract it
result -= decodeSingle(uRoman.charAt(i));
} else {
//add it
result += decodeSingle(uRoman.charAt(i));
}
}
//decode the last character, which is always added
result += decodeSingle(uRoman.charAt(uRoman.length() - 1));
return result;
}
public static void main(String[] args) {
System.out.println(decode("MCMXC")); //1990
System.out.println(decode("MMVIII")); //2008
System.out.println(decode("MDCLXVI")); //1666
}
我想用以下兩個數組設置程序。 我的想法是我可以比較的任何用戶輸入是all_numerals
(即用戶輸入V
相比, V
,那么這將給它的索引值。一旦我們有了指數的價值,我們可以比較的價值all_values
index顯然,我還將需要一個循環來遍歷用戶輸入。
# put this somewhere in the data section
all_numerals: .asciiz "IVXLCDMivxlcdm"
all_values: .byte 1, 5, 10, 50, 100, 500, 1000, 1, 5, 10, 50, 100, 500, 1000
我的問題是:您是否必須將all_numerals
和all_values
的值插入寄存器中,還是可以按原樣比較數組? 這對MIPS來說是全新的,這是最有效和合乎邏輯的方法嗎?
您可以通過嵌套的if-check替換switch並擺脫子功能調用。 這樣,您無需保留羅馬字母與數據塊中對應字母之間的映射。 它們可以被硬編碼為常量。 此外,這種優化使我的速度提高了兩倍:
public static int decode(String roman) {
int result = 0;
String uRoman = roman; //case-insensitive
int prevPart = -1;
for(int i = 0; i < uRoman.length(); i++) {//loop over all but the last character
int curPart = 0;
int letter = (int)uRoman.charAt(i);
if (letter >= 'a' && letter <= 'z')
letter -= (int)'a' - (int)'A'; // toUpper emulation
if (letter <= (int)'I') {
if (letter == (int)'C') {
curPart = 100;
} else if (letter == (int)'D') {
curPart = 500;
} else if (letter == (int)'I') {
curPart = 1;
}
} else if (letter <= (int)'M') {
if (letter == (int)'L') {
curPart = 50;
} else if (letter == (int)'M') {
curPart = 1000;
}
} else if (letter == (int)'V') {
curPart = 5;
} else if (letter == (int)'X') {
curPart = 10;
}
if (prevPart > 0) {
//if this character has a lower value than the next character
if (prevPart < curPart) {
//subtract it
result -= prevPart;
} else {
//add it
result += prevPart;
}
}
prevPart = curPart;
}
//decode the last character, which is always added
result += prevPart;
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.