[8kyu]I love you, a little , a l
2017-07-02 本文已影响37人
君肄塵
该算法题来自于 codewars【语言: javascript】,翻译如有误差,敬请谅解~
- 场景
还记得在校园里的时候,遇见女孩拿着一朵花,撕开花瓣时,每次撕下一片花瓣,都会说出以下每个短语:
I love you
a little
a lot
passionately
madly
not at all
- 任务
对于给定数量的花,判断撕到最后一片瓣花会说什么短语,这里花瓣数量一直大于0。
- 解答【如解答有误,欢迎留言指正~】
- 其一
const howMuchILoveYou =(nbPetals) => {
const Array = ['I love you','a little','a lot','passionately','madly','not at all'];
return !(nbPetals%Array.length) ? Array[Array.length-1] : Array[nbPetals%Array.length -1];
}
- 其二
const howMuchILoveYou = n => ['I love you', 'a little', 'a lot', 'passionately', 'madly', 'not at all'][(n - 1) % 6]
- 其三
function howMuchILoveYou(nbPetals) {
let phrases = ['I love you','a little','a lot','passionately','madly','not at all'];
let index = (nbPetals % phrases.length) -1
if( index < 0 ) index = phrases.length + index
return phrases[index];
}