Decimal Conversion error

穿精又带淫゛_ 提交于 2019-11-29 15:25:46

This is the problem:

8^7

The ^ operator doesn't do what you think it does. It does binary XOR...

However, I'd say that the whole design is distinctly suspect. An int value isn't "in" octal or any other base - it's just an integer. The number ten is the number ten, whether that's exressed as "10" in decimal, "A" in hex or "12" in octal. If you've got a sequence of characters which you want to parse as octal digits, the input to the method should be a String, not an int.

Since your method accepts an integer (commonly represented in a String representation as decimal), and what you're outputting is also an integer, you've not really turned into "an octal integer", you've changed it into some other integer completely. You're trying to correctly convert your integer into an octal, and then incorrectly interpreting that octal as a decimal.

If wish to convert an integer into it's octal string representation, you could simply use the following method:

public static String convert(int number) {
    Integer.toOctalString(number);
}

And, if you truly want to return an int that represents that octal String parsed as if it was decimal, you could simply do this:

public static int convert(int number) {
    return Integer.parseInt(Integer.toOctalString(number));
}

If you have repetitive code, you might consider a loop.

public static void main(String... args) {
    for (long i = 7, j = 7; i > 0; i = i * 10 + 1, j = j * 8 + 1) {
        long c = convert(i);
        if (c != j)
            throw new AssertionError(i + ": " + c + " != " + j);
        System.out.println(i + " = > " + j);
    }
}

public static long convert(long octal) {
    long ret = 0;
    for (long i = 1000000000000000000L, j = 1L << (3 * 18); i > 0; i /= 10, j >>= 3)
        ret += j * (octal / i % 10);
    return ret;
}

prints

7 = > 7
71 = > 57
711 = > 457
7111 = > 3657
71111 = > 29257
711111 = > 234057
7111111 = > 1872457
71111111 = > 14979657
711111111 = > 119837257
7111111111 = > 958698057
71111111111 = > 7669584457
711111111111 = > 61356675657
7111111111111 = > 490853405257
71111111111111 = > 3926827242057
711111111111111 = > 31414617936457
7111111111111111 = > 251316943491657
71111111111111111 = > 2010535547933257
711111111111111111 = > 16084284383466057
7111111111111111111 = > 128674275067728457

You have an underlying misconception that's going to keep messing you up.

There is no such thing as an "octal number", per se. An int isn't decimal, or roman numerals, or octal - it's just a number.

An "octal number" really means "a string containing the octal representation of a number".

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!