首页 > 解决方案 > 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 :(');
    }
}

我没有找到错误,我不知道如何解决。

:(

标签: dartbigint

解决方案


如果将程序粘贴到 dartpad.dartlang.org 中,则会收到警告:

使用不相关类型引用的相等运算符 `==` 调用 - 第 7 行

因此,也许将第 7 行从:

while( number != 0 )

while (number != BigInt.zero)

(也可以考虑用 格式化你的代码dart format,它会让习惯阅读 Dart 的人更容易阅读)。


推荐阅读