一种比较容易理解的解法 | 进制转换

进制转换

https://www.nowcoder.com/practice/0337e32b1e5543a19fa380e36d9343d7

import java.io.*;
import java.math.BigInteger;
public class Main {
    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s;

        while ((s = br.readLine()) != null) {
            System.out.println(toBinary(s));
        }
    }
    public static String divide2(String s) {
        int carry = 0;// 记录首部除2余数
        StringBuilder sb = new StringBuilder();
        // 将s除2,从首部开始
        for (char c : s.toCharArray()) {
            int x = c - '0' + carry * 10;
            sb.append(x / 2);
            carry = x % 2;
        }
        // 为什么不考虑最后carry=1?因为在方法 中取最后%2余数
        // 去首部0
        return sb.substring(sb.charAt(0) == '0' ? 1 : 0, sb.length()).toString();
    }

    public static String toBinary(String s) {
        StringBuilder sb = new StringBuilder();
        while (!s.equals("")) {
            int lastChar = s.charAt(s.length() - 1) - '0'; //每次只需计算末尾
            sb.append(lastChar % 2);
            s = divide2(s);
        }
        return sb.reverse().toString();//结果反转
    }



}

全部评论
点赞 回复 分享
发布于 03-15 17:11 江苏

相关推荐

狄文君:多段项目经历 + 专业技能拉满,这简历很能打,坐等好消息!
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务