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的更多相关文章

  1. Web site collections

    Integration 伯乐在线 极客头条 Hacker News Stack Overflow RFC Search Security Python Hacker - Freebuf PrimalS ...

  2. 递归调用里的性能问题(js)

    说明 这是在codewars.com上刷的一道js练习题,在此做个记录 问题描述 The Fibonacci sequence is traditionally used to explain tre ...

  3. Concurrent.Thread.js

    (function(){ if ( !this.Data || (typeof this.Data != 'object' && typeof this.Data != 'functi ...

  4. Quiz(贪心,快速幂乘)

    C. Quiz time limit per test 1 second memory limit per test 256 megabytes input standard input output ...

  5. mysql----JOIN Quiz

    JOIN quiz game id mdate stadium team1 team2 1001 8 June 2012 National Stadium, Warsaw POL GRE 1002 8 ...

  6. mysql----Nested SELECT Quiz

     Nested SELECT quiz bbc name region area population gdp Afghanistan South Asia 652225 26000000   Alb ...

  7. (转载)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 ...

  8. Visual Studio Code 代理设置

    Visual Studio Code (简称 VS Code)是由微软研发的一款免费.开源的跨平台文本(代码)编辑器,在十多年的编程经历中,我使用过非常多的的代码编辑器(包括 IDE),例如 Fron ...

  9. 我们是怎么做Code Review的

    前几天看了<Code Review 程序员的寄望与哀伤>,想到我们团队开展Code Review也有2年了,结果还算比较满意,有些经验应该可以和大家一起分享.探讨.我们为什么要推行Code ...

随机推荐

  1. 【js】再谈移动端的模态框实现

    移动端模态框的机制因为与PC的模态框机制一直有所区别,一直是许多新人很容易踩坑的地方,最近笔者作为一条老咸鱼也踩进了一个新坑中,真是平日里代码读得太粗略,故而写上几笔,以儆效尤. 故事的起因是这样的, ...

  2. phpstorm设置代码片段

    tab 向后推进 shift+tab 向前推进 ctrl+d 复制整行 ctrl+Y删除整行 代码片段就是代码快捷键,如果你设置了www.baidu.com这些内容,但是不想一直重复的打,可以设置个代 ...

  3. Angular JS (2)

    通过Angular JS的官方教学文档,了解 routeProvider 的用法, angular.module('aaa').config(['$locationProvider','$routeP ...

  4. 61配置nanopim1plus的HDMI为1080p输出

    61配置nanopim1plus的HDMI为1080p输出 大文实验室/大文哥 壹捌陆捌零陆捌捌陆捌贰 21504965 AT qq.com 完成时间:2018/4/4 10:21 版本:V1.1 开 ...

  5. CAD与用户互在图面上得到一个矩形框(com接口VB语言)

    主要用到函数说明: MxDrawXCustomFunction::ExApp_CutDwg 与用户互在图面上得到一个矩形框,详细说明如下: 参数 说明 IN DOUBLE dX1 保存范围的左下角位置 ...

  6. Redis系列(六)--为什么这么快?

    Redis作为一个基于key-value的NoSQL数据库,最显著的特点存取速度非常快,官方说可以达到10W OPS,但是Redis为何这么快? 1.开发语言 Redis使用C语言进行编写的,而Uni ...

  7. js数组的处理

    //重写Array中的indexOf方法,获取数组中指定值的元素的索引 Array.prototype.indexOf = function (val) { for (var i = 0; i < ...

  8. Oracle 11g 字符集修改

    服务端字符集修改 1.确认服务端字符集 select userenv('language') from dual; 2.修改服务端字符集 首先以 DBA 身份登录 Oracle.Windows 系统下 ...

  9. BZOJ 1058: [ZJOI2007]报表统计 multiset + 卡常

    Code: #include<bits/stdc++.h> #define maxn 600000 #define inf 1000000000 using namespace std; ...

  10. python安装外部模块Django

    Windows安装Django模块: 由于本人安装的Python版本是Python3.7,所以安装命令为:pip3 install django /pip3 install django安装过程中出现 ...