我想在整数结束时找出0的数字。 假设任何人进入 2020它应该计数1 ,如果数字 2000它应该显示3 等;
我试过以下但没有达到我想要的目的:(
Console.WriteLine("Enter Number :");
int num = int.Parse(Console.ReadLine());
int count = 0;
for (int i = 1; i < num.ToString().Count(); i++)
{
//some logic
}
Console.WriteLine("Zero in the tail is :");
Console.WriteLine(count);
答案 0 :(得分:16)
你不会在你的循环中改变任何东西 - 所以基本上,在每次迭代时它会增加Count
或者它不会,并且它每次都会做同样的事情 - 所以Count
将是字符串的长度,或者它将是0.
我在文本操作方面可以想到的最简单的选择是:
string text = num.ToString();
int count = text.Length - text.TrimEnd('0').Length;
然而,不使用文本操作,您可以使用除法和余数操作:
int count = 0;
// Keep going while the last digit is 0
while (num > 0 && num % 10 == 0)
{
num = num / 10;
count++;
}
请注意,对于数字0,这将产生0的计数...而第一种方法将计数为1(因为0.ToString()
是&#34; 0&#34;)。调整任何一段代码以满足您的要求:)
答案 1 :(得分:1)
你也可以采用数学方式
int n = int.Parse(Console.ReadLine());
int totalzero = 0 ;
while(n > 0){
int digit = n % 10;
if(digit == 0)
totalzero++;
else
break;
n = n / 10;
}
答案 2 :(得分:1)
你可以通过从后面迭代字符串来做到这一点:
var strN = 40300.ToString();
int count = 0;
for (var i = strN.Length - 1; strN[i] == '0'; --i, ++count) ;
Console.WriteLine("Result : " + count);
答案 3 :(得分:1)
int GetTrailingZerosFromInteger(int no)
{
if (no == 0)
return 1;
int count = 0;
while(no % 10 == 0)
{
no /= 10;
count++;
}
return count;
}
答案 4 :(得分:0)
由于32位整数最多可以有9个零,因此您可以以非常愉快的方式展开循环:
int digits =
num == 0 ? 0 :
num % 1000000000 == 0 ? 9 :
num % 100000000 == 0 ? 8 :
num % 10000000 == 0 ? 7 :
num % 1000000 == 0 ? 6 :
num % 100000 == 0 ? 5 :
num % 10000 == 0 ? 4 :
num % 1000 == 0 ? 3 :
num % 100 == 0 ? 2 :
num % 10 == 0 ? 1 : 0;