【问题标题】:Converting a number to a user chosen base将数字转换为用户选择的基数
【发布时间】:2016-01-08 18:17:48
【问题描述】:

我想制作一个接收数字和基本系统的东西,以便它将数字转换为从 2 到 16 不同基数的数字。

例如stdin 将是 67 和 2,这意味着用户希望程序将数字 67 更改为二进制形式。标准输出将是 1000010

所以我首先编写了以下代码以使其运行。该程序接受一个数字并将其转换为二进制格式。

public class ChangeofBase { 
    public static void main(String[] args) { 
        // read in the command-line argument
        int n = Integer.parseInt(args[0]); 
        // set v to the largest power of two that is <= n
        int v = 1; 
        while (v <= n/2) {
            v *= 2;
        }
        // check for presence of powers of 2 in n, from largest to smallest
        while (v > 0) {
            // v is not present in n 
            if (n < v) {
                System.out.print(0);
            }

            // v is present in n, so remove v from n
            else {
                System.out.print(1);
                n -= v;
            }
            // next smallest power of 2
            v /= 2;
        }
        System.out.println();
    }
}

如何修改上述代码以执行以下功能?

输入一个数字n 和一个基数k,这样n 将转换为基数k 中的一个数字

再一次,k 必须介于 2 和 16 之间。基数 2 和基数 16。二进制和十六进制。谢谢!

编辑:我想在不使用内置函数的情况下执行此操作。硬编码
编辑 2:我是 Java 新手。所以我想坚持基本的东西,比如定义变量、while 循环和 foo 循环、if-else 和打印。并解析命令行参数。我相信这就是我们对这个程序所需要的,但如果我错了,请纠正我

【问题讨论】:

    标签: java base


    【解决方案1】:

    你可以使用Integer.toString(int i, int radix).

    【讨论】:

    • 嗨,我想对此进行硬编码,即没有内置函数
    • 我最初的答案不是你想要的,我已经更新了。
    • 你能举个例子说明我是如何将它融入我的代码的吗?
    • 应该是单行 System.out.println(Integer.toString(args[0], args[1])); 假设 args[1] 是基础。
    • 是的 :) 又犯了一个错误!需要先解析参数。这是一个工作程序:goo.gl/roGVkG
    【解决方案2】:

    除了Java内置的函数,你可以在Java中使用简单的除法和取模运算来实现。

    public class IntBaseConverter {
    public static void main(String[] args) {
        convert(Integer.parseInt(args[0]), Integer.parseInt(args[1]));
    }
    
    public static void convert(int decimalValue, int base) {
        String result = "";
        while (decimalValue >= base) {
            result = decimalValue % base + result;
            decimalValue /= base;
        }
        result = decimalValue + result;
    
        System.out.println(result);
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多