使用java语言实现将10进制转化为2进制

一、描述

使用java语言,不不调用十进制转成二进制函数Integer.toBinaryString(int i),
将10进制的int转为2进制的string。(改编自code hunt 平台)

二、基本思路

主要分为两部分:

1.通过除二和模二将输入的数一位一位的转化为二进制

2.写pow函数,用来将每一位依次存储下来

三、代码

 1 public class Pro {
 2     public static String Puzzle(int n) {
 3 
 4         String str;
 5         int x = 0;
 6         int count = 0;
 7         while ((n / 2) != 0) {
 8             x = x + n % 2 * pow(count);
 9             n /= 2;
10             count++;
11         }
12         x = x + 1 * pow(count);
13         str = String.valueOf(x);
14         return str;
15 
16     }
17 
18     public static int pow(int n) {
19         int sum = 1;
20         for (int i = 0; i < n; i++) {
21             sum = sum * 10;
22         }
23         return sum;
24     }
25 }
原文地址:https://www.cnblogs.com/airjasonsu/p/4458081.html