代码大战中的STRONGN强数特殊数字系列2单词问题

问题描述

强数是数字的阶乘之和等于数字本身的数字。

例如:145,因为 1! + 4! + 5! = 1 + 24 + 120 = 145

这是我的代码,它通过了除一个测试之外的大多数测试

#include <string>
using namespace std; 

string strong_num (int number )
{
  int sum = 0;
  
  while(number != 0) {
    int last = number % 10;
    number /= 10;
    sum+= last * (last-1);
  }
  
  if(sum == number)
    return "STRONG!!!!";
  else
    return "Not Strong !!";
}

我的代码有什么问题?

解决方法

令我惊讶的是,您根本没有通过任何测试用例。一方面,您在将FactoryBeanpublic class SampleFactoryBean implements FactoryBean<SampleObject> { @Override public SampleObject getObject() throws Exception { return new SampleObject(); } @Override public Class<?> getObjectType() { return SampleObject.class; } @Override public boolean isSingleton() { return true; } } 进行比较之前就将其销毁了,另一方面,您的逻辑也有缺陷。

尝试一下:

number

Live demo

sum替换为int factorial (int x) { int result = 1; while (x > 1) { result *= x; x--; } return result; } string strong_num (int number) { int sum = 0; int x = number; while (x != 0) { int digit = x % 10; sum += factorial (digit); x /= 10; } if (sum == number) return "STRONG!!!!"; else return "Not Strong !!"; } ,以便能够测试更大的数字。

,

有两个问题: 首先-您要先更改number的值,然后再将其与sum进行比较, 第二-您使用的last * (last-1)不是阶乘的定义,阶乘的定义是factorial(x) = 1 * 2 * 3 * ... * x

int factorial (int x) {
    if(x < 2) return 1;
    return x * factorial(x - 1);
}

string strong_num (int number)
{
    int sum = 0;
    int x = number;
  
    while (x != 0) {
        int last = x % 10;
        sum += factorial (last);
        x /= 10;
    }
  
    if (sum == number)
        return "STRONG!!!!";
    else
        return "Not Strong !!";
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...