It works with small numbers like 0 & 1 but it failed the final test.
I'm getting the following error:
System.OverflowException : Value was either too large or too small for an Int64.
Stack Trace
at System.Number.ParseInt64(ReadOnlySpan`1 value, NumberStyles options, NumberFormatInfo numfmt)
at System.Convert.ToInt64(String value)
at Kata.CountBits(Int32 n)
at BitCounting.CountBits()
I don't understand how it can be too big for a 64bits int?
using System;
using System.Linq;
public class Kata
{
//This function adds each bit of a given integer n
public static int CountBits(int n)
{
//checking for negative number input
if(n>0){
long total=0, lastDigit=0, bitsInInt;
string bits = Convert.ToString(n, 2);
Int64.TryParse(bits, out bitsInInt);
while (bitsInInt>0){
lastDigit = bitsInInt%10;
total = total+lastDigit;
bitsInInt = bitsInInt/10;
}
return Convert.ToInt32(total);
}
return 0;
}
}