kame
kame

Reputation: 21990

FormatException when parsing BigInteger

I try to solve a problem at codewars.com where I add two BitInteger. Here is the Link

With my code:

using System;
using System.Numerics;
using System.Globalization;

public static class Kata
{
    public static string sumStrings(string a, string b)
    {
      Console.WriteLine(a + " " + b);
      BigInteger numbera = BigInteger.Parse(a);
      BigInteger numberb = BigInteger.Parse(b);
      BigInteger numberc;

      numberc = numbera + numberb;
      Console.WriteLine(numberc);
      return numberc.ToString();
    }
}

I get an FormatException-Error:

System.FormatException : The value could not be parsed. 
at System.Numerics.BigNumber.ParseBigInteger (System.String value, NumberStyles style, System.Globalization.NumberFormatInfo info) [0x00000] in <filename unknown>:0 
at System.Numerics.BigInteger.Parse (System.String value) [0x00000] in <filename unknown>:0 
at Kata.sumStrings (System.String a, System.String b) [0x00000] in <filename unknown>:0 
at CodeWarsTest.Test6 () [0x00000] in <filename unknown>:0

but the output seems to be correct.

input: string 1 --> "712569312664357328695151392" 
input: string 2 --> "8100824045303269669937"
output: sum --> 712577413488402631964821329

Why do I get a FormatException here??

EDIT: The code works in MonoDevelopment but not on the Codewars.com-site.

Upvotes: 3

Views: 2087

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726919

It is a problem with their site. One of the tests passes you an invalid input (an empty string) for the first parameter.

Here is the code that catches this problem:

BigInteger na, nb;
if (!BigInteger.TryParse(a, out na)) {
    Console.WriteLine("A is invalid: '{0}'",a);
}
if (!BigInteger.TryParse(b, out nb)) {
    Console.WriteLine("B is invalid: '{0}'", b);
}
var nc = na + nb;
return nc.ToString();

It prints

A is invalid: ''

for test number 5.

Upvotes: 5

Related Questions