问题描述
嗨,
我已经编写了一个程序来解决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的人更容易理解。)