code wars quiz: toInteger
Your task is to program a function which converts any input to an integer.
Do not perform rounding, the fractional part should simply be discarded.
If converting the input to an integer does not make sense (with an object, for instance), the function should return 0 (zero).
Also, Math.floor(), parseInt() and parseFloat() are disabled for your unconvenience.
Onegaishimasu!
function toInteger(n) {
var arr, i, ret = 0, sgn = 1, mul;
var pos, front, matches, swap;
if(typeof n == 'string' || typeof n == 'number'){
n += '';
if(n.slice(0, 1) == '-'){
sgn = -1;
n = n.slice(1);
}
if(matches = /^(\d*\.\d+)e(-?\d+)$/i.exec(n)){
front = matches[1];
mul = toInteger(matches[2]);
pos = front.indexOf('.');
arr = front.split('');
if(mul >= 0){
for(i = 0; i < mul; ++i){
swap = arr[pos + i];
arr[pos + i] = arr[pos + i + 1];
arr[pos + i + 1] = swap;
if(arr[arr.length - 1] == '.')arr.push('0');
}
}else{
if(pos < -mul){
for(i = -mul - pos; i > 0; --i){
arr.unshift('0');
}
}
for(i = 0; i > mul; --i){
swap = arr[pos + i];
arr[pos + i] = arr[pos + i - 1];
arr[pos + i - 1] = swap;
}
}
}else{
arr = n.split('');
}
for(i = 0; i < arr.length; ++i){
if(arr[i] >= '0' && arr[i] <= '9'){
ret = ret * 10 + (arr[i] - '0');
}else if(arr[i] == 'e' || arr[i] == 'E'){
mul = arr.slice(i + 1).join('');
if(!/^-?\d+$/.test(mul)){
ret = 0;
break;
}
mul = toInteger(mul);
ret *= (mul > 0? Math.pow(10, mul): Math.pow(.1, - mul));
ret = toInteger(ret);
break;
}else if(arr[i] == '.'){
break;
}else{
ret = 0;
break;
}
}
}
else if(n === true)return 1;
return ret * sgn;
}
It passes all my unit tests, can not figure out what is wrong with my code.
Test.assertEquals(toInteger(1), 1)
Test.assertEquals(toInteger('1e-2'), 0)
Test.assertEquals(toInteger('-20e-2'), 0)
Test.assertEquals(toInteger('-.98720e-2'), 0)
Test.assertEquals(toInteger('-200.67e-2'), -2)
Test.assertEquals(toInteger('-200.67e3'), -200670)
Test.assertEquals(toInteger('-200.67e0'), -200)
Test.assertEquals(toInteger('-1234e-5'), 0)
Test.assertEquals(toInteger('1234e7'), 12340000000)
Test.assertEquals(toInteger('-200e-2'), -2)
Test.assertEquals(toInteger('e-0'), 1)
Test.assertEquals(toInteger('.3e1'), 3)
Test.assertEquals(toInteger('5000e-2'), 50)
Test.expect(toInteger("4.55") === 4)
后面我修了一下,简化了这部分的逻辑,加入了对16进制、8进制和单元素数组的处理……最后终于被迫用eval破了这个kata。
看了其他人的答案,发现问题的关键是用位运算符,它自带Int32的操作……
例如~~n, n >> 0, n | 0, n ^ 0,这些都是可行的直接切割整数部分的技巧。
code wars quiz: toInteger的更多相关文章
- Web site collections
Integration 伯乐在线 极客头条 Hacker News Stack Overflow RFC Search Security Python Hacker - Freebuf PrimalS ...
- 递归调用里的性能问题(js)
说明 这是在codewars.com上刷的一道js练习题,在此做个记录 问题描述 The Fibonacci sequence is traditionally used to explain tre ...
- Concurrent.Thread.js
(function(){ if ( !this.Data || (typeof this.Data != 'object' && typeof this.Data != 'functi ...
- Quiz(贪心,快速幂乘)
C. Quiz time limit per test 1 second memory limit per test 256 megabytes input standard input output ...
- mysql----JOIN Quiz
JOIN quiz game id mdate stadium team1 team2 1001 8 June 2012 National Stadium, Warsaw POL GRE 1002 8 ...
- mysql----Nested SELECT Quiz
Nested SELECT quiz bbc name region area population gdp Afghanistan South Asia 652225 26000000 Alb ...
- (转载)ASP.NET Quiz Answers: Does Page.Cache leak memory?
原文地址:http://blogs.msdn.com/b/tess/archive/2006/08/11/695268.aspx "We use Page.Cache to store te ...
- Visual Studio Code 代理设置
Visual Studio Code (简称 VS Code)是由微软研发的一款免费.开源的跨平台文本(代码)编辑器,在十多年的编程经历中,我使用过非常多的的代码编辑器(包括 IDE),例如 Fron ...
- 我们是怎么做Code Review的
前几天看了<Code Review 程序员的寄望与哀伤>,想到我们团队开展Code Review也有2年了,结果还算比较满意,有些经验应该可以和大家一起分享.探讨.我们为什么要推行Code ...
随机推荐
- 认识BACnet协议
一.什么是BACnet? BACnet,Building Automation and Control networks的简称,即楼宇自动化与控制网络.是用于智能建筑的通信协议. 一般楼宇自控设备从功 ...
- spring Cache /Redis 缓存 + Spring 的集成示例
spring Cache https://www.ibm.com/developerworks/cn/opensource/os-cn-spring-cache/ spring+redis 缓存 ht ...
- 【洛谷4721】【模板】分治FFT(CDQ分治_NTT)
题目: 洛谷 4721 分析: 我觉得这个 "分治 FFT " 不能算一种特殊的 FFT ,只是 CDQ 分治里套了个用 FFT (或 NTT)计算的过程,二者是并列关系而不是偏正 ...
- MyEclipse日志文件目录
MyEclipse存放日志的目录为: <Workspace_Root>/.metadata/.log 在该目录下存放了日志的存档和当前日志,通过该日志可以查看MyEclipse的错误信息.
- Android 性能优化(15)网络优化( 11)Manipulating Broadcast Receivers On Demand
Manipulating Broadcast Receivers On Demand This lesson teaches you to Toggle and Cascade State Chang ...
- 关于 VS 调用存储过程加载很慢和SQL 执行很快的那些事
执行同样的存储过程,调用同样的参数 在VS 中调用存储过程和传参后,到数据加载需要20秒或更多, 在SQL直接调用则不到一秒,同一个存储过程为什么有这么大的区别呢? 原因:存储过程计划失效的原因 产生 ...
- PHP fSQL Tutorial
PHP fSQL Tutorial This tutorial is designed to give a brief overview of the PHP fSQL API since versi ...
- jsp学习笔记 - 内置对象 application
---恢复内容开始--- 1.application一般用this.getServletContext()替代 2.appllication有一个非常有用的函数 getRealPath(),获取绝对路 ...
- PHPStorm+XDebug进行调试
笔者的开发环境如下: Windows8.1+Apache+PhpStorm+XDebug+Firefox(XDebug helper 1.4.3插件). 一.XDebug安装配置 (1)下载XDebu ...
- vue基础---条件渲染
(1)v-if条件渲染 v-if 指令用于条件性地渲染一块内容.这块内容只会在指令的表达式返回 truthy 值的时候被渲染. 可以用 v-else 添加一个“else 块”: ①表达式 <di ...