zoukankan      html  css  js  c++  java
  • 使用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 }
  • 相关阅读:
    Mybatis中#{}与${}的区别:
    JDBC
    JavaScript与jQuery的区别
    JavaScript 高级
    AdminLTE
    servlet过滤器与监听器
    数据库连接池
    大对象数据LOB的应用
    Serializable
    泛型
  • 原文地址:https://www.cnblogs.com/airjasonsu/p/4458081.html
Copyright © 2011-2022 走看看