zwhu / blog

嘛,写 blog 也要遵守基本法。
MIT License
66 stars 2 forks source link

在 codewars 升阶了,撒花 #11

Open zwhu opened 8 years ago

zwhu commented 8 years ago

有两个月没有去 codewars 刷过题,最近总收到 codewars 的邮件说 codewars 已经支持 es6 了,下午登录 codewars 发现还差几分就可以升到 3 阶,于是花了一下午的时间做了最后一道 4 阶题,顺利升了阶,撒花!🎉🎉

下面就是我的最后一道四阶题:

Description:

You have to create a function that takes a positive integer number and returns the next bigger number formed by the same digits:

nextBigger(12)==21
nextBigger(513)==531
nextBigger(2017)==2071

If no bigger number can be composed using those digits, return -1:

nextBigger(9)==-1
nextBigger(111)==-1
nextBigger(531)==-1

我的解法如下:

var exch = (a, k) => {
  return [a[k], ...a.slice(0,k),...a.slice(k+1)]
}

var nextBigger = (n) => {
 if(n < 11) return -1
 var a = Array.from(`${n}`).map(v=>v|0)
   , i = a.length

 while(--i) {
   if(a[i] > a[i-1]) {
    var c = a.slice(i-1).sort((a,b) => (a|0) > (b|0))
      , k = c.indexOf(a[i])
    for(var j = 1; j < c.length; j++) {
      if(c[j] > a[i-1] && c[j] < c[k])
        k = j
    }

     return Number([...a.slice(0, i-1), ...exch(c, k)].join(''))
   }
 }
  return -1
}
kujian commented 8 years ago

看不懂,这些都是es6的写法吗?

zwhu commented 8 years ago

@kujian es6的写法,可以放到chrome控制台直接运行的