dart - Dart 中的程序可以使用 int 但无法使用 BigInt 解决
问题描述
你好,
我写了一个用 Python 解决难题的程序。为了在 Dart 中取得进步,我尝试用这种语言编写,但不幸的是,我没有在那里解决:
谜题链接: https ://www.codingame.com/training/easy/happy-numbers
我的代码它可以工作但不包括 BigInt (所以不是最后两个测试)
import 'dart:io';
int step(int number)
{
int result = 0;
int ten = 10;
while( number != 0 )
{
result = result + (number % ten )*(number % ten );
number = (number ~/ ten );
}
return result;
}
bool solve(int out, int number)
{
int resultat = number;
while( true )
{
resultat = step(resultat);
if( resultat == 1 )
return true;
if( resultat == 4 )
return false;
}
}
void main() {
int N = int.parse(stdin.readLineSync());
for (int i = 0; i < N; i++) {
int x = int.parse(stdin.readLineSync());
bool res = solve(x,x);
print( res == true ? '$x :)' : '$x :(');
}
}
我用 BigInt 证实了这一点
import 'dart:io';
BigInt step(BigInt number)
{
BigInt result = BigInt.parse('0');
BigInt ten = BigInt.parse('10');
while( number != 0 )
{
result = result + (number % ten )*(number % ten );
number = (number ~/ ten );
}
return result;
}
bool solve(BigInt out, BigInt number)
{
BigInt resultat = number;
while( true )
{
resultat = step(resultat);
if( resultat == BigInt.parse('1') )
return true;
if( resultat == BigInt.parse('4') )
return false;
}
}
void main() {
int N = int.parse(stdin.readLineSync());
for (int i = 0; i < N; i++) {
BigInt x = BigInt.parse(stdin.readLineSync());
bool res = solve(x,x);
print( res == true ? '$x :)' : '$x :(');
}
}
我没有找到错误,我不知道如何解决。
:(
解决方案
如果将程序粘贴到 dartpad.dartlang.org 中,则会收到警告:
使用不相关类型引用的相等运算符 `==` 调用 - 第 7 行
因此,也许将第 7 行从:
while( number != 0 )
至
while (number != BigInt.zero)
(也可以考虑用 格式化你的代码dart format
,它会让习惯阅读 Dart 的人更容易阅读)。
推荐阅读
- typescript - Scala 片段到 TypeScript(如何转换抽象类型成员)
- php - Woocommerce :为每个项目生成一个唯一密钥并将其发送到订单电子邮件中
- python - 如何忽略 pandas.reset_option('all') 的警告
- swift - 是否可以打印屏幕上呈现的 UI 内容 | 迅速
- java - AspectJ 环绕调用,包括方法调用后的方法体
- maven - 查找从 JCenter 下载了哪些 Maven 依赖项?
- usb - USB 或磁盘加密算法不依赖于操作系统
- python - 需要 telnet 中的登录功能?
- typescript - 如何解决“没有重载匹配此调用”。使用passport.serializeUser时出错?
- mysql - 如何理解 Mysql 中的这种锁定机制 [update A=x where A=y]