if

1 -> 1
100 -> 3
-100 -> 4

String Length

using System;
class Program
{
static void Main()
{
*// Write number of digits in the integers using two methods.*
int[] values = {1, 100, -100};
foreach (int i in values)
{
int result1 = GetIntegerDigitCountString(i);
int result2 = GetIntegerDigitCount(i);
Console.WriteLine(i + *"="* + result1 + *" "* + result2);
}
}
static int GetIntegerDigitCountString(int value)
{
*// Version 1: get digit count with ToString.*
return value.ToString().Length;
}
static int GetIntegerDigitCount(int valueInt)
{
*// Version 2: use if-statements.*
double value = valueInt;
int sign = 0;
if (value < 0)
{
value = -value;
sign = 1;
}
if (value <= 9)
{
return sign + 1;
}
if (value <= 99)
{
return sign + 2;
}
if (value <= 999)
{
return sign + 3;
}
if (value <= 9999)
{
return sign + 4;
}
if (value <= 99999)
{
return sign + 5;
}
if (value <= 999999)
{
return sign + 6;
}
if (value <= 9999999)
{
return sign + 7;
}
if (value <= 99999999)
{
return sign + 8;
}
if (value <= 999999999)
{
return sign + 9;
}
return sign + 10;
}
}1=1 1
100=3 3
-100=4 4

ToString

Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.

No updates found for this page.