博客
关于我
【牛客】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/

    你可能感兴趣的文章
    Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
    查看>>
    org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
    查看>>
    sql查询中 查询字段数据类型 int 与 String 出现问题
    查看>>
    org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
    查看>>
    org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
    查看>>
    sqlserver学习笔记(三)—— 为数据库添加新的用户
    查看>>
    org.apache.http.conn.HttpHostConnectException: Connection to refused
    查看>>
    org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
    查看>>
    org.apache.ibatis.exceptions.PersistenceException:
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>
    org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    查看>>
    org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
    查看>>
    org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:processDebugManifest'
    查看>>
    org.hibernate.HibernateException: Unable to get the default Bean Validation factory
    查看>>
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
    查看>>
    org.springframework.amqp.AmqpConnectException:java.net.ConnectException:Connection timed out:connect
    查看>>
    org.springframework.beans.factory.BeanDefinitionStoreException
    查看>>
    org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
    查看>>