如何用Java计算整数中的尾随零? (例如:234000 => 3个零) [英] How to count in Java the trailing zeros from an Integer? (Ex: 234000 => 3 zeros)

查看:100
本文介绍了如何用Java计算整数中的尾随零? (例如:234000 => 3个零)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题几乎是自我解释的。 :)

The title is pretty much self explanatory. :)

1232 => 0
1231030 => 1
2000 => 3
34444400000 => 5


推荐答案

如果它适合 int / long ,只需检查模10的数字是否为0并保留一个计数器:

If it fits into an int/long, just check if the number modulo 10 is 0 and keep a counter:

long x = ...
if (x == 0) {
    return 0;
}
int counter = 0;
while (x % 10 == 0) {
    counter++;
    x /= 10;
}

它太大了,不适合 long ,将其存储在 String 中,并从最后一个char中计算零:

It it's too big to fit in long, store it in a String and count zeroes from the last char:

String s = ...
counter = 0;
while(counter < s.length() && s.charAt(s.length() - 1 - counter) == '0') {
    counter++;
}

这篇关于如何用Java计算整数中的尾随零? (例如:234000 =&gt; 3个零)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆