From 94aa6b6fb92475ec192f6f830714422b51ce4633 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=BD=A9=E8=BE=95=E9=BE=99=E5=84=BF?= Date: Fri, 3 Mar 2023 10:49:39 +0800 Subject: [PATCH] =?UTF-8?q?=E9=9D=A2=E8=AF=95=E9=A2=98=2005.02:=E4=BA=8C?= =?UTF-8?q?=E8=BF=9B=E5=88=B6=E6=95=B0=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../editor/cn/BianryNumberToStringLcci.java | 64 +++++++++++++++++++ .../doc/content/BianryNumberToStringLcci.md | 27 ++++++++ 2 files changed, 91 insertions(+) create mode 100644 src/main/java/leetcode/editor/cn/BianryNumberToStringLcci.java create mode 100644 src/main/java/leetcode/editor/cn/doc/content/BianryNumberToStringLcci.md 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