汇总一个数字,直到变成1位数JS [英] Sum up a number until it becomes 1 digit JS
问题描述
在标记重复的注释之前,它不是.其他人并没有寻找和我完全一样的东西.
最简单的方法是用javascript总结一个数字,直到只剩一位数字为止.例如:您输入5678,然后脚本将其加在一起(5 + 6 + 7 + 8)并得到26,但是由于它的位数超过1,因此再次将其添加并得到2 + 6 = 8.
是否可以使用任意大小的数字来执行此操作?脚本可以得到多紧凑?
如果您正在寻找短片,那就很难打败了
var n = 5678;
sum = n % 9 || 9;
console.log(sum)
如果您对它的工作方式感到好奇,请参阅:铸造九个数字. >
Before you mark duplicate note that it isn't. Others didn't look for the exact same thing as me.
What is the most compact possible way to sum up a number in javascript until there is only one digit left. For example: You input 5678 then the script adds it together (5+6+7+8) and gets 26, but since its more than 1 digit it adds it again and gets 2+6=8.
Is there anyway to do this with a number of any size? And how compact can the script get?
If you're looking for short, it's hard to beat:
var n = 5678;
sum = n % 9 || 9;
console.log(sum)
If you're curious about how that works, see: casting out nines.
这篇关于汇总一个数字,直到变成1位数JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!