diff --git a/src/main/java/leetcode/editor/cn/BianryNumberToStringLcci.java b/src/main/java/leetcode/editor/cn/BianryNumberToStringLcci.java new file mode 100644 index 0000000..f2c5af6 --- /dev/null +++ b/src/main/java/leetcode/editor/cn/BianryNumberToStringLcci.java @@ -0,0 +1,64 @@ +//

二进制数转字符串。给定一个介于0和1之间的实数(如0.72),类型为double,打印它的二进制表达式。如果该数字无法精确地用32位以内的二进制表示,则打印“ERROR”。

+// +//

示例1:

+// +//
+// 输入:0.625
+// 输出:"0.101"
+//
+// +//

示例2:

+// +//
+// 输入:0.1
+// 输出:"ERROR"
+// 提示:0.1无法被二进制准确表示
+//
+// +//

 

+// +//

提示:

+// +// +// +//
Related Topics
  • 位运算
  • 数学
  • 字符串

  • 👍 99
  • 👎 0
  • +package leetcode.editor.cn; + +// 面试题 05.02:二进制数转字符串 +public class BianryNumberToStringLcci { + public static void main(String[] args) { + Solution solution = new BianryNumberToStringLcci().new Solution(); + // TO TEST + solution.printBin(0.625); + } + + //leetcode submit region begin(Prohibit modification and deletion) + class Solution { + public String printBin(double num) { + String str = "0."; + String strNum = "" + num; + while (strNum.endsWith("0")) { + strNum = strNum.substring(0, strNum.length() - 1); + } + while (num > 0 && strNum.endsWith("5")) { + num *= 2; + if (num >= 1) { + str += 1; + num -= 1; + } else { + str += 0; + } + strNum = "" + num; + while (strNum.endsWith("0")) { + strNum = strNum.substring(0, strNum.length() - 1); + } + } + return strNum.equals("0.") ? str : "ERROR"; + } + } +//leetcode submit region end(Prohibit modification and deletion) + +} diff --git a/src/main/java/leetcode/editor/cn/doc/content/BianryNumberToStringLcci.md b/src/main/java/leetcode/editor/cn/doc/content/BianryNumberToStringLcci.md new file mode 100644 index 0000000..5d00058 --- /dev/null +++ b/src/main/java/leetcode/editor/cn/doc/content/BianryNumberToStringLcci.md @@ -0,0 +1,27 @@ +

    二进制数转字符串。给定一个介于0和1之间的实数(如0.72),类型为double,打印它的二进制表达式。如果该数字无法精确地用32位以内的二进制表示,则打印“ERROR”。

    + +

    示例1:

    + +
    + 输入:0.625
    + 输出:"0.101"
    +
    + +

    示例2:

    + +
    + 输入:0.1
    + 输出:"ERROR"
    + 提示:0.1无法被二进制准确表示
    +
    + +

     

    + +

    提示:

    + + + +
    Related Topics
  • 位运算
  • 数学
  • 字符串

  • 👍 99
  • 👎 0
  • \ No newline at end of file