0

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;
  }  
}
Doc
  • 13
  • 4
  • The source code does not match the exception message. Please [edit] your question to include a [mcve] and the matching exception message with the stack trace to your question. – Progman Mar 05 '21 at 20:28
  • @Progman ? Looks like [mcve] to me - 1000% should fail for large enough numbers "100...0" (2^31 as binary string ) definitely can't be parsed as Int64 – Alexei Levenkov Mar 05 '21 at 20:32
  • Duplicate shows proper ways to do that, if you really want to convert it to string - https://stackoverflow.com/questions/10391481/number-of-occurrences-of-a-character-in-a-string – Alexei Levenkov Mar 05 '21 at 20:37

0 Answers0