将阿拉伯语转换为罗马数字时出现问题

问题描述

我的程序将阿拉伯数字转换为罗马数字时遇到问题。起初一切都很好。但是当我输入更大的数字时,我会得到正确的输出加一个额外的数字

这是我的代码:

public class Persist {

/**
 *
 * @param number
 * @return finalAnswer
 */
public String solution(int number) {


    String nS = Integer.toString(number);
    String[] numbArray = nS.split("");
    String reverse = "";
    int count = 0;


    for(int y = numbArray.length - 1; y > -1; y--) {
        count++;

        int digit = Integer.parseInt(numbArray[y]);

        if(count == 1) {
            reverse = reverse.concat(rome("I","V","X",digit,reverse));
        }
        if(count == 2) {
            reverse = reverse.concat(rome("X","L","C",reverse));
        }
        if(count == 3) {
            reverse = reverse.concat(rome("C","D","M",reverse));
        }
    }

    //reverse a string
    String finalAnswer = "";
    for(int i = reverse.length() - 1; i >= 0; i--) {
        finalAnswer = finalAnswer + reverse.charAt(i);
    }

    return finalAnswer;
}



/**
 *
 * @param a,b,c - different Roman numerals
 * @param digit2 = digit
 * @param toReverse = reverse
 * @return toReverse = reverse
 */
public String rome(String a,String b,String c,int digit2,String toReverse) {

    if (digit2 == 0) {
        //do nothing
    }
    else if (digit2 > 0 && digit2 < 4) {
        for(int i = 0; i < digit2; i++) {
            toReverse = toReverse.concat(a);
        }
    }
    else if (digit2 == 4) {
        toReverse = toReverse.concat(b + a);
    }
    else if (digit2 > 4 && digit2 < 9) {
        for(int i = 0; i < (digit2 - 5); i++) {
            toReverse = toReverse.concat(a);
        }
        toReverse = toReverse.concat(b);
    }
    else if (digit2 == 9) {
        toReverse = toReverse.concat(c + a);
    }

    return toReverse;
}

}

这是我的测试

import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class Testing {



private Persist conversion = new Persist();

@Test
public void shouldConvertToRoman() {
    assertEquals("solution(1) should equal to I","I",conversion.solution(1));
    assertEquals("solution(4) should equal to IV","IV",conversion.solution(4));
    assertEquals("solution(6) should equal to VI","VI",conversion.solution(6));

    assertEquals("solution(501) should equal to DI","DI",conversion.solution(501));
    assertEquals("solution(87) should equal to LXXXVII","LXXXVII",conversion.solution(87));
    assertEquals("solution(578) should equal to DLXXVIII","DLXXVIII",conversion.solution(578));
}
}

输出:

org.junit.ComparisonFailure: solution(501) should equal to DI 
Expected :DI
Actual   :DIIII

因此,它可以很好地转换较小的数字(包括1到10),但是当数字较大时,它看起来像转换并输出数字的最后一位两次。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...