code wars quiz: toInteger

Your task is to program a function which converts any input to an integer.javascript

Do not perform rounding, the fractional part should simply be discarded.java

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.code

Onegaishimasu!orm

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.blog

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。ip

看了其餘人的答案,發現問題的關鍵是用位運算符,它自帶Int32的操做……input

例如~~n, n >> 0, n | 0, n ^ 0,這些都是可行的直接切割整數部分的技巧。string

相關文章
相關標籤/搜索