Binary Representation
2016-07-21 13:29
357 查看
Given a (decimal - e.g. 3.72) number that is passed in as a string, return the binary representation that is passed in as a string. If the fractional part of the number can not be represented accurately in binary with at most 32 characters, return
Example
For n =
For n =
分析:
分成两个部分,整数部分用%和/,小数部分 *2 如果 <1 就为0,基数=基数;大于1,就为1,基数=基数-1
ERROR.
Example
For n =
"3.72", return
"ERROR".
For n =
"3.5", return
"11.1".
分析:
分成两个部分,整数部分用%和/,小数部分 *2 如果 <1 就为0,基数=基数;大于1,就为1,基数=基数-1
比如: 0.6*2=1.2>0 那么就为1 基数=1.2-1=0.2 0.2*2=0.4<0 那么就为0,基数=0.4 0.4*2=0.8<0,那么就为0,基数=0.8 0.8*2=1.6>0 那么就为1,基数为1.6-1=0.6 : : : : 所以5.6可以表示为:101.1001
public class Solution { /** *@param n: Given a decimal number that is passed in as a string *@return: A string */ public String binaryRepresentation(String n) { int intPart = Integer.parseInt(n.substring(0, n.indexOf('.'))); double decPart = Double.parseDouble(n.substring(n.indexOf('.'))); String intstr = ""; String decstr = ""; if (intPart == 0) intstr += '0'; while (intPart > 0) { int c = intPart % 2; intstr = c + intstr; intPart = intPart / 2; } int count = 0; while (decPart > 0.0 && count <= 32) { double r = decPart * 2; if (r >= 1.0) { decstr += '1'; decPart = r - 1.0; }else { decstr += '0'; decPart = r; } count++; } if (count > 32) return "ERROR"; return decstr.length() > 0? intstr + "." + decstr : intstr; } }
相关文章推荐
- #2# 使用\连接
- 基础拾忆------委托详解
- [字符编码]Invalid byte 1 of 1-byte UTF-8 sequence终极解决方案
- hdu1495 非常可乐--BFS
- 解决线上问题办法
- 初学安卓路之初识ListView
- PHP查找字符串中的字符串并替换
- 喜欢的橘子
- Vsftp 服务器搭建
- LAMP平台
- Jni中C++和Java的参数传递
- 25岁到55岁,如何规划人生最重要的三个十年
- 优先队列priority_queue的比较函数
- Spring的IoC
- CodeForces 253D Table with Letters - 2 减小复杂度的技巧+交替枚举
- Linux Kernel 之 symbol
- linux mysql install
- 在Centos7上部署安装RobotFramework
- 17.1.1.5 Creating a Data Snapshot Using mysqldump 创建一个快照使用mysqldump:
- Android: 使用JitPack发布你的Github开源库