Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

在 codewars 升阶了,撒花 #11

Open
zwhu opened this issue Nov 15, 2015 · 2 comments
Open

在 codewars 升阶了,撒花 #11

zwhu opened this issue Nov 15, 2015 · 2 comments

Comments

@zwhu
Copy link
Owner

zwhu commented Nov 15, 2015

有两个月没有去 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
Copy link

kujian commented Nov 23, 2015

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

@zwhu
Copy link
Owner Author

zwhu commented Nov 23, 2015

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants