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

本文提供了三个Codewars JavaScript练习题的解决方案,包括判断是否为平方数、寻找下一个完全平方数及预测年龄等算法问题。

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

codewars-js练习

2021/2/2

github 地址

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

【1】<7kyu>【You’re a square!】

Given an integral number, determine if it’s a square number:

example

-1  =>  false
 0  =>  true
 3  =>  false
 4  =>  true
25  =>  true
26  =>  false

solution

<script type="text/javascript">
 		var isSquare = function(n){
 			console.log(n);
 			let i = 0;
 			if(n!=0){
 				while (n > i * i) {
					i++;
				}
				return i * i === n;
 			}
 			return true;
 		}

 		// 验证
		console.log(isSquare(-1));// false
		console.log(isSquare(25));//true
		console.log(isSquare(0));//false
	</script>
【2】<7kyu>【Find the next perfect square!】

You might know some pretty large perfect squares. But what about the NEXT one?

Complete the findNextSquare method that finds the next integral perfect square after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer.

If the parameter is itself not a perfect square then -1 should be returned. You may assume the parameter is positive.

找下一个完全平方数

example

findNextSquare(121) --> returns 144
findNextSquare(625) --> returns 676
findNextSquare(114) --> returns -1 since 114 is not a perfect

solution

<script type="text/javascript">
 		function findNextSquare(sq) {
 			// console.log(sq);
			for(var i=0;i>-1;i++){
				var square = i*i;
        		if(square==sq){
        			// console.log('i',i);
        			return (i+1)*(i+1);
        		}else if(square>sq){
        			return -1;
        		} 
			}
 		}

 		// 验证
		console.log(findNextSquare(121));// 144
		console.log(findNextSquare(625));// 676
		console.log(findNextSquare(114));// -1
	</script>
【3】<7kyu>【Predict your age!】

In honor of my grandfather’s memory we will write a function using his formula!

  • Take a list of ages when each of your great-grandparent died.
  • Multiply each number by itself.
  • Add them all together.
  • Take the square root of the result.
  • Divide by two.

列出你曾祖父去世时的年龄。把每个数单独乘起来。把它们加在一起。对结果开平方根。除以2。

example

predictAge(65, 60, 75, 55, 60, 63, 64, 45) === 86

solution

<script type="text/javascript">
 		function predictAge(age1,age2,age3,age4,age5,age6,age7,age8){
 			let arr = [age1,age2,age3,age4,age5,age6,age7,age8];
 			console.log(arr);
 			let sum = 0;
 			for(var i=0;i<arr.length;i++){
 				sum +=(arr[i] * arr[i]);
 			}
 			return Math.floor(Math.sqrt(sum)/2);
 		}

 		// 验证
		console.log(predictAge(65, 60, 75, 55, 60, 63, 64, 45));// 86
	</script>

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值