当前位置: 首页 > news >正文

leetcode-面试题 05.02. Binary Number to String LCCI

Description

Given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print “ERROR”.

Example1:

 Input: 0.625Output: "0.101"

Example2:

Input: 0.1
Output: “ERROR”
Note: 0.1 cannot be represented accurately in binary.
Note:

This two charaters "0." should be counted into 32 characters.
The number of decimal places for num is at most 6 digits

Solution

How to represent a decimal into binary? Like how we represent integers into binary, first choose the maximum power of 2, put 1 to that digit, minus the power from num, then iterate until num=0num=0num=0

It’s even easier to implement when it comes to decimal. Because we get the maximum power of 2 first (0.5)

Time complexity: o(n)o(n)o(n)
Space complexity: o(1)o(1)o(1)

Code

class Solution:def printBin(self, num: float) -> str:res = []n = 1while len(res) <= 30 and num != 0:cur_binary_num = 1 / (2 ** n)if num >= cur_binary_num:res.append('1')num -= cur_binary_numelse:res.append('0')n += 1return '0.{}'.format(''.join(res)) if num == 0 else 'ERROR'
http://www.lryc.cn/news/26343.html

相关文章:

  • C语言函数阐述
  • 二叉树——把二叉搜索树转换为累加树
  • Java使用DFA算法实现敏感词过滤
  • UG NX二次开发(C#)-外挂 - 配置文件说明(.men文件/.rtb文件/.trb文件)
  • Web3中文|日本元宇宙经济“狂飙”
  • @Autowired和@Resource到底有什么区别
  • 2023年最新阿里云服务器价格表出炉(精准收费标准及配置价格表)
  • ElasticSearch - SpringBoot整合ES实现文档的增删改操作
  • 嵌入式 LVGL移植到STM32F4
  • VSCode——SSH免密登录
  • python未来应用前景怎么样
  • webpack基本使用和开发环境配置
  • 3.2 http协议
  • 页面访问升级出错怎么解决
  • leetcode 181. 超过经理收入的员工
  • 任务类风险漏洞挖掘思路
  • 2023年Dubbo常见面试题
  • 星光2开发板使用ECR6600U无线wifi网卡的方法
  • 【ArcGIS Pro二次开发】(11):面要素的一键拓扑
  • 【实现点击下载按钮功能 Objective-C语言】
  • 界面控件DevExpress WinForm——轻松构建类Visual Studio UI(三)
  • 项目实战-瑞吉外卖day01(B站)
  • Linux 学习整理(使用 iftop 查看网络带宽使用情况 《端口显示》)
  • Vue3创建项目(四)axios封装及接口配置
  • 【算法笔记】递归与回溯
  • 蓝桥杯备赛——Echarts学习
  • 动态规划--最长公共子串
  • 【运筹优化】剩余空间法求解带顺序约束的二维矩形装箱问题 + Java代码实现
  • 第四阶段15-关于权限,处理解析JWT时的异常,跨域请求,关于Spring Security的认证流程
  • 毕业设计 基于51单片机的指纹红外密码电子锁