Ad
  • Custom User Avatar

    As a string '1' comes before '2' and also before '9'.
    That's why '180' comes before '90' and '11' comes before '2000'

  • Custom User Avatar

    You should stop at 10, not add 1 to 0 and get 1. Generally speaking, you should only sum digits once per number.

  • Custom User Avatar

    This comment is hidden because it contains spoiler information about the solution

  • Custom User Avatar

    In Java or C/C++, for example, sign integer type (32 bit) max value is: 2147483647.
    signed long (long long in C/C++) type (64 bit) max value is: 9223372036854775807

    Just to add some C++ trivia: The C++ standard only says that long long must have at least 64 bits. Depending on your compiler/platform, you can end up with 96, 128, or something strange like 108 bits. Also, while the standard permits two complements, implementations are free to choose another binary representation, see 3.9.1§7 and footnote 49 (C++11).

    Furthermore, the behaviour on max_int + 1 is undefined, see section 5§4:

    If during the evaluation of an expression, the result is not mathematically defined or not in the range of
    representable values for its type, the behavior is undefined. [Note: most existing implementations of C ++
    ignore integer overflows. [...] —end note ]

    So std::numeric_limits<int>::max() + static_cast<int>(1) may or may not lead to std::numeric_limits<int>::min(). It's undefined.

  • Custom User Avatar

    Hello. I think you're wrong and you got overflow. Because Fibonacci's sequence can't take negative value. It begins with 1, 1, 2, 3, 5, 8... and so on.

    You have negative value, because value in 300th is "222232244629420445529739893461909967206666939096499764990979600" this value bigger than types integer or long can store (maybe BigInteger or BigDecimal, but I haven't tested it).

    In Java or C/C++, for example, sign integer type (32 bit) max value is: 2147483647.
    signed long (long long in C/C++) type (64 bit) max value is: 9223372036854775807 (note that signed 64 bit is smaller than 300th Fibonacci number). What happens if give more than can be stored?

    If I'll try making something like this in Java:

    int i = Integer.MAX_VALUE + 1;
    System.out.println(i);
    

    I will get overflow, in this case "i" will store "-2147483648". Why "-2147483648", not "2147483647"? Because the first bit is responsible for the sign.

    2147483647 in binary:
    0|1111111 11111111 11111111 11111111
    2147483647 + 1 in binary:
    1|0000000 00000000 00000000 00000000 
    

    You can read more about signed/unsigned numbers here and here