【Codewars】<7kyu>By 3, or not by 3? That is the question . . .

博客围绕判断字符串表示的数字能否被3整除展开。介绍小学学过的技巧,即把数中所有整数相加,和除以3无余数则原数可被3整除。所有测试用例参数是表示大于0值的字符串,还包含题解内容。

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

题目

A trick I learned in elementary school to determine whether or not a number was divisible by three is to add all of the integers in the number together and to divide the resulting sum by three. If there is no remainder from dividing the sum by three, then the original number is divisible by three as well.
Given a series of digits as a string, determine if the number represented by the string is divisible by three.
You can expect all test case arguments to be strings representing values greater than 0.


小学时学过一个技巧来判断一个数是否可以被3整除,就是把这个数中的所有整数相加,然后把所得的和除以3。如果和除以3没有余数,那么原始数也可以被3整除。
给定一系列数字作为字符串,确定字符串表示的数字是否可以被3整除。
所有测试用例参数都是表示大于0的值的字符串。

例子

"123"      -> true
"8409"     -> true
"100853"   -> false
"33333333" -> true
"7"        -> false

题解一

// 解法一:
function divisibleByThree(str){
    return str.split('').reduce((sum,i)=> parseInt(sum)+parseInt(i)) % 3 == 0
}

题解二

// 解法二:
function divisibleByThree(str){
    return [...str].reduce((s,d)=>+d+s,0)%3===0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值