闲着没事写了个简单的十进制转二进制的算法,很简单,个人记录一下,不妥之处请指正。

public static String toBinaryString(int j) {
        if (j < 0) {
            throw new NumberFormatException("不支持负数");
        }
        double i = (double) j;
        StringBuilder sb = new StringBuilder();
        while (true) {
            if (i % 2 == 0)
                sb.append("0");
            else
                sb.append("1");
            int result = (int) (i / 2);
            if (result == 1) {
                sb.append("1");
                break;
            }
            i = (double) result;
        }
        char[] chars = sb.toString().toCharArray();
        int len = chars.length - 1;
        for (int a = 0; a <= len; a++) {
            char c = chars[a];
            char d = chars[len];
            chars[a] = d;
            chars[len] = c;
            len--;
        }
        return new String(chars);
    }

相关文章:

  • 2021-10-06
  • 2021-12-27
  • 2022-12-23
  • 2021-10-12
  • 2021-12-17
  • 2021-11-26
猜你喜欢
  • 2022-01-09
  • 2021-12-02
  • 2021-11-01
  • 2021-08-11
  • 2022-12-23
  • 2021-04-28
  • 2021-05-24
相关资源
相似解决方案