简体   繁体   English

如何将 Integer 转换为没有 Integer.toString Function 的字符串 [暂停]

[英]How to Convert an Integer to a String without Integer.toString Function [on hold]

This is an extension to a previous question of mine, but I'm required to do this problem without this function.这是我之前的问题的扩展,但我需要在没有这个 function 的情况下解决这个问题。 I have to use recursion only.我必须只使用递归。 Any thoughts?有什么想法吗?

An example;一个例子; 20A would be: 20A 将是:

2 x 12^2 + 0 x 12^1 + 10 x 12^0 = 2 x 144 + 0 x 12 + 10 x 1 = 288 + 0 + 10 = 298 2 x 12^2 + 0 x 12^1 + 10 x 12^0 = 2 x 144 + 0 x 12 + 10 x 1 = 288 + 0 + 10 = 298

public class Duodecimal {
      public static String toBase12(int n) {
        if (n < 10)
            return Integer.toString(n);
        if (n == 10)
            return "A";
        if (n == 11)
            return "B";
        return toBase12(n / 12) + toBase12(n % 12);
      }
    }

Well, you've figured it out for n == 10. Surely you can use the same technique for n == 9. If you want an alternate idea, imagine you have the string '0123456789AB'.好吧,你已经计算出了 n == 10。当然你可以对 n == 9 使用相同的技术。如果你想要一个替代的想法,想象你有字符串 '0123456789AB'。 String has a method to ask for the character at a given index. String 有一种方法来请求给定索引处的字符。 NOw, what digit is at position '9' in that string?现在,该字符串中 position '9' 的数字是多少? What is at 10? 10点是什么? Exactly.确切地。 This method is charAt .这个方法是charAt

I bet you can finish this homework with this hint:)我打赌你可以用这个提示完成这个作业:)

With a little thought, you could extend this to convert any base from 2 thru 16.稍加思考,您可以扩展它以转换从 2 到 16 的任何基数。

  1. Add a second parameter to the method and call it base or radix在方法中添加第二个参数并将其命名为baseradix
  2. Define a final String of digits as "0123456789ABCDEF"将最终的digits字符串定义为"0123456789ABCDEF"
  3. Put in appropriate check(s) to ensure the radix is within an allowable range.进行适当的检查以确保radix在允许的范围内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM