亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將羅馬數字轉換為整數

將羅馬數字轉換為整數

飲歌長嘯 2021-06-21 08:10:13
我正在關注的羅馬數字到整數轉換器:https://www.selftaughtjs.com/algorithm-sundays-converting-roman-numerals/我嘗試將 Javascript 函數轉換為 Java:public class RomanToDecimal {public static void main (String[] args) {    int result = 0;    int[] decimal = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};    String[] roman = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};    // Test string, the number 895    String test = "DCCCXCV";    for (int i = 0; i < decimal.length; i++ ) {        while (test.indexOf(roman[i]) == 0) {            result += decimal[i];            test = test.replace(roman[i], "");        }    }    System.out.println(result);}}輸出是615,這是不正確的。請幫助我理解我哪里出錯了。
查看完整描述

2 回答

?
汪汪一只貓

TA貢獻1898條經驗 獲得超8個贊

您test = test.replace(roman[i], "");將所有出現的“C”替換為“”,因此在找到第一個“C”并將總數加 100 后,您將消除所有剩余的“C”,并且從不計算它們。因此,您實際上計算了 的值"DCXV",即615。


您應該只替換roman[i]起始索引為 0 的出現,您可以通過替換來實現:


test = test.replace(roman[i], "");

和:


test = test.substring(roman[i].length()); // this will remove the first 1 or 2 characters

                                          // of test, depending on the length of roman[i]

以下:


int result = 0;

int[] decimal = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};

String[] roman = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};


// Test string, the number 895

String test = "DCCCXCV";


for (int i = 0; i < decimal.length; i++ ) {

    while (test.indexOf(roman[i]) == 0) {

        result += decimal[i];

        test = test.substring(roman[i].length());

    }

}

System.out.println(result);

印刷:


895


查看完整回答
反對 回復 2021-06-23
?
12345678_0001

TA貢獻1802條經驗 獲得超5個贊

test = test.replace(roman[i], "");

這將替換每次出現。相反,您應該只截斷字符串開頭(位置 0)的出現。

嘗試使用substring而不是替換,并將長度作為參數傳遞roman[i]


查看完整回答
反對 回復 2021-06-23
  • 2 回答
  • 0 關注
  • 189 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號