Java任务:实现将数字转换为其他数字系统的方法

时间:2015-12-22 13:26:58

标签: java

我的任务状况:

  

实现方法convertNumberToOtherNumerationSystem()的逻辑,它应该将数字number.getDigit()从一个数字系统(numerationSystem)转换为另一个数字系统(expectedNumerationSystem)。

     

如果数字不正确则抛出NumberFormatException,例如:number" 120"使用数字系统" 2"。

     

验证number.getDigit() - 正整数。

这是我的代码:

班级解决方案

public class Solution {
    public static void main(String[] args) {
        Number number = new Number(NumerationSystemType._10, "6");
        Number result = convertNumberToOtherNumerationSystem(number, NumerationSystemType._2);
        System.out.println(result);    //expected 110
    }

    public static Number convertNumberToOtherNumerationSystem(Number number, NumerationSystem expectedNumerationSystem) {
        return null;
    }

Enum NumerationSystemType

public enum NumerationSystemType implements NumerationSystem {
    _16,
    _12,
    _10,
    _9,
    _8,
    _7,
    _6,
    _5,
    _4,
    _3,
    _2;

    @Override
    public int getNumerationSystemIntValue() {
        return Integer.parseInt(this.name().substring(1));
    }
}

班级编号

public class Number {
    private NumerationSystem numerationSystem;
    private String digit;

    public Number(NumerationSystem numerationSystem, String digit) {
        this.numerationSystem = numerationSystem;
        this.digit = digit;
    }

    public NumerationSystem getNumerationSystem() {
        return numerationSystem;
    }

    public String getDigit() {
        return digit;
    }

    @Override
    public String toString() {
        return "Number{" +
            "numerationSystem=" + numerationSystem +
            ", digit='" + digit + '\'' +
            '}';
    }

接口NumerationSystem

public interface NumerationSystem {
    int getNumerationSystemIntValue();
}

我将不胜感激任何帮助和任何建议。

1 个答案:

答案 0 :(得分:0)

您需要使用源编号的编号系统来解析数字,然后使用预期的编号系统来生成新的数字。

public static Number convertNumberToOtherNumerationSystem(Number number, NumerationSystem expectedNumerationSystem) {
    // Get an Integer using the numeration system to parse the digits.
    int value = Integer.parseInt(number.getDigit(), number.getNumerationSystem().getNumerationSystemIntValue());
    // Convert it to new form.
    return new Number(expectedNumerationSystem, Integer.toString(value, expectedNumerationSystem.getNumerationSystemIntValue()));
}

这确实产生110 - 实际上它打印 Number {numerationSystem = _2,digit ='110'}