my github地址,上面有做的习题记录,不断更新…
剃干净的头发用“-”表示,散乱的头发用“/”表示。你的任务是检查头部是否有散落的头发并把它们清除掉。
example:
0 hairs --> "Clean!" 1 hair --> "Unicorn!" 2 hairs --> "Homer!" 3-5 hairs --> "Careless!" >5 hairs --> "Hobo!" "------/------" you shoud return: ["-------------", "Unicorn"]
solution
<script type="text/javascript"> function bald(x){ console.log(x) var len = x.length; var s = x.match(/[/]/g); var temp = []; if(s == null) return [x,'Clean!'] var num = s.length; for(var i=0;i<len;i++){ temp.push('-'); } var str = temp.join(''); var result = [str]; if(num == 0)result.push('Clean!'); else if(num == 1)result.push('Unicorn!') else if (num == 2)result.push('Homer!') else if (num>=3&& num<=5)result.push('Careless!') else result.push('Hobo!') return result; } // 验证 // console.log(bald('/---------'));// ['----------', 'Unicorn!'] // console.log(bald('/-----/-'));//['--------', 'Homer!'] // console.log(bald('--/--/---/-/---'));// ['---------------', 'Careless!'] console.log(bald('-----'));//['----','Clean!'] </script>
Johnny想通过计算所有的握手次数来了解今年参与的人数。
该函数获取握手次数,并返回执行这些握手所需的最小人数(一对农民只握手一次)。
握手次数 | 最小人数 |
---|---|
0 | 1 |
1 | 2 |
3 | 3 |
6 | 4 |
example:
6//4 7//5
solution
<script type="text/javascript"> function getParticipants(handshakes){ // console.log(handshakes) x = (1 + Math.sqrt(1+8*handshakes))/2 return Math.ceil(x) } // 验证 console.log(getParticipants(0));// 1 console.log(getParticipants(1));// 2 console.log(getParticipants(3));//3 console.log(getParticipants(6));//4 console.log(getParticipants(7));//5 </script>