您的位置:首页 > 其它

Sum of Digits / Digital Root

2015-07-09 15:30 435 查看

SumofDigits/DigitalRoot

Inthiskata,youmustcreatea
digitalroot
function.

Adigitalrootistherecursivesumofallthedigitsinanumber.Givenn,takethesumofthedigitsofn.Ifthatvaluehastwodigits,continuereducinginthiswayuntilasingle-digitnumberisproduced.Thisisonlyapplicabletothenaturalnumbers.

Here'showitworks(Rubyexamplegiven):

digital_root(16)
=>1+6
=>7

digital_root(942)
=>9+4+2
=>15...
=>1+5
=>6

digital_root(132189)
=>1+3+2+1+8+9
=>24...
=>2+4
=>6

digital_root(493193)
=>4+9+3+1+9+3
=>29...
=>2+9
=>11...
=>1+1
=>2


usingSystem;
usingSystem.Linq;

publicclassNumber
{
publicintDigitalRoot(longn)
{
//Yourawesomecodehere!
while(n>9)
{
n=n.ToString().Select(c=>Convert.ToInt32(c.ToString())).Sum();
}
return(int)n;
}
}




publicclassNumber
{
publicintDigitalRoot(longn)
{
return(int)((n-1)%9+1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: