博客
关于我
【牛客】KY72 Digital Roots(数根)
阅读量:205 次
发布时间:2019-02-28

本文共 625 字,大约阅读时间需要 2 分钟。

数字根的计算方法可以通过数根公式直接求解,而无需逐位相加。数根公式为:当n=0时,数字根为0;否则,数字根等于(n-1)%9 +1。

数字根公式

数字根可以通过以下公式直接计算:[ \text{数字根} = \begin{cases}0 & \text{如果 } n = 0 \(n-1) % 9 + 1 & \text{其他情况}\end{cases} ]

代码实现

int digitSum(int n) {    if (n == 0) {        return 0;    }    return (n - 1) % 9 + 1;}

主函数

#include 
int digitSum(int n) { if (n == 0) { return 0; } return (n - 1) % 9 + 1;}int main() { int number; while (scanf("%d", &number) != EOF) { printf("数字根为:%d\n", digitSum(number)); } return 0;}

优化说明

  • 简洁高效:通过数根公式直接计算,避免了循环或递归,代码简短且运行效率高。
  • 避免重复计算:每次读取输入后立即计算,减少了多次计算的开销。
  • 易于维护:代码结构清晰,单一责任原则明确,每个函数都有明确的功能。
  • 转载地址:http://xmoi.baihongyu.com/

    你可能感兴趣的文章
    OpenWrt固件编译刷机完全总结
    查看>>
    Open××× for Linux搭建之二
    查看>>
    Open×××有线网络时使用正常,无线网络时使用报错的解决方案
    查看>>
    Opera Mobile Classic Emulator
    查看>>
    Operation not supported on read-only collection 的解决方法 - [Windows Phone开发技巧系列1]
    查看>>
    OperationResult
    查看>>
    Operations Manager 2007 R2系列之仪表板(多)视图
    查看>>
    operator new and delete
    查看>>
    operator new 与 operator delete
    查看>>
    operator() error
    查看>>
    OPPO K3在哪里打开USB调试模式的完美方法
    查看>>
    oppo后端16连问
    查看>>
    OPPO软件商店APP侵权投诉流程
    查看>>
    Optional用法与争议点
    查看>>
    Optional类:避免NullPointerException
    查看>>
    Optional讲解
    查看>>
    ORA-00069: cannot acquire lock
    查看>>
    ORA-00923: 未找到要求的 FROM 关键字
    查看>>
    ORA-00932: inconsistent datatypes: expected - got NCLOB【ORA-00932: 数据类型不一致: 应为 -, 但却获得 NCLOB 】【解决办法】
    查看>>
    ORA-00942 表或视图不存在
    查看>>