codewars练习(javascript)-2021/2/1

本文介绍了三道Codewars JavaScript练习题的解决方案,包括字谜检测、四舍五入到最近的5的倍数及累加字符串等,通过实际代码示例详细解释了每道题目的解题思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

codewars-js练习

2021/2/1

github 地址

my github地址,上面有做的习题记录,不断更新…

【1】<7kyu>【Anagram Detection】

An anagram is the result of rearranging the letters of a word to produce a new word (see wikipedia).

Note: anagrams are case insensitive

Complete the function to return true if the two arguments given are anagrams of each other; return false otherwise.

字谜是将一个单词的字母重新排列以产生一个新单词的结果。注意:字谜不区分大小写。如果给定的两个参数是彼此的字谜,则完成函数返回true;否则返回false。

example

"foefet" is an anagram of "toffee"

"Buckethead" is an anagram of "DeathCubeK"

solution

<script type="text/javascript">
		var isAnagram = function(test, original) {
			// 全部转为大写或小写方便比较,此处使用的全部小写
			// 排序
			var tStr = test.toLowerCase().split('').sort().join('');
			var oStr = original.toLowerCase().split('').sort().join('');
			console.log(tStr,oStr);
			if(oStr===tStr){
				return true;
			}
			return false;
		};
	
		// 验证
		console.log(isAnagram("foefet", "toffee"));//true
		console.log(isAnagram("Twoo", "WooT"));// true
		console.log(isAnagram("dumble", "bumble"));//false
		console.log(isAnagram("ound", "round"));// false
		console.log(isAnagram("Buckethead", "DeathCubeK"));// true
		console.log(isAnagram("apple", "pale"));// false
	</script>
【2】<7kyu>【Round up to the next multiple of 5】

Given an integer as input, can you round it to the next (meaning, “higher”) multiple of 5?

四舍五入到下一个5的倍数

example

input:    output:
0    ->   0
2    ->   5
3    ->   5
12   ->   15
21   ->   25
30   ->   30
-2   ->   0
-5   ->   -5
etc.

solution

<script type="text/javascript">
 		function roundToNext5(n){
 			console.log('n',n);
 			if(n %5 !=0){
 				return (Math.floor(n/5)+1)*5;
 			}
 			return n;
 		}
 		
		// 验证
		[
		  [0,0],
		  [1,5],
		  [3,5],
		  [5,5],
		  [7,10],
		  [39,40],
		  [-2,0],
		  [-5,-5]
		].forEach(
		  ([x,out])=> console.log(roundToNext5(x), out)
		);
	</script>
【3】<7kyu>【Mumbling】

example

accum("abcd") -> "A-Bb-Ccc-Dddd"
accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
accum("cwAt") -> "C-Ww-Aaa-Tttt"

solution

<script type="text/javascript">
 		function accum(s) {
 			// console.log(s);
 			var result = [s[0]];
 			for(var i=1;i<s.length;i++){
 				var ss = s[i].toUpperCase() + new Array(i+1).join(s[i].toLowerCase());
				// console.log(ss);
 				result.push(ss);
 			}
 			return result.join('-');
 		}

 		// 验证
		console.log(accum("ZpglnRxqenU"));// "Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu"
	</script>

知识点:重复n次

function repeatString(str,n) {
	return new Array(n+1).join(str);
}
repeatString("a",3) // "aaa"

以上为自己思路供大家参考,可能有更优的思路。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值