数字计数方法

huangapple go评论71阅读模式
英文:

Digits count method

问题

I created a method that should count digits of numbers but it is only working when the first digit is not zero.
For example it gives for the number 01011100 the result 7 instead of 8, and for the number 00101111 6 instead of 8.
I am very thankful for any help!.

public static int countDigits(int x) {
    int y = 0;
    while (!(x == 0)) {
        x /= 10;
        y++;
    }

    return y;
}

The method starts counting digits only after the first "1" comes.

英文:

I created a method that should count digits of numbers but it is only working when the the first digit is not zero.
For example it gives for the number 01011100 the result 7 instead of 8, and for the number 00101111 6 instead of 8.
I am very thankful for any help!.

public static int countDigits(int x) {
	int y=0;
	while (!(x== 0)) 
		{
		x /= 10;
	    y ++;
	    }

	return y;
}

The method starts counting digits only after the firs "1" comes.

答案1

得分: 4

00101111 不是一个 int 值可以表示的东西。字面上来说,类似于:

int x = Integer.parseInt("00101111");
int y = Integer.parseInt("101111");

x 和 y 的每一位都是相同的。在这里,不可能区分 xy。事实上,无法将 400000000000 存储在 int 中(它不支持那么大的数值;int 只能表示在 -2^31 到 +2^31-1 之间的整数)。同样也无法单独存储 00101111。这就是使 int 如此高效的原因,它们只能表示非常具体的内容。而 00101111 不是其中之一,只有 101111 是。

如果您需要存储这样的概念,那么它不是一个数字。它更像是一个有限的字符串;请使用 String(在这种情况下,您可以调用 str.length() 来确定其中有多少个字符),或者编写自己的数据类型来表示它。

如果您获得一个 int 值并被要求计算数字的个数,并且您希望得到一个 '8' 的答案,因为该 int 是使用 00101111 创建的,那是完全不可能的 - 您需要更改给您提供该 int 的任何代码,并将其更改为为您提供 String 或其他特定的数据类型。

英文:

00101111 isn't a thing that an int value can represent. Literally. Something like:

int x = Integer.parseInt("00101111");
int y = Integer.parseInt("101111");

x and y are bit for bit identical. It is impossible to tell the difference between x and y here. There is in fact no possible way to store, say, 400000000000 in an int (it doesn't go that far; ints can store any integral number between -2^31 and +2^31-1). There also is no way to store specifically 00101111 either. That is what makes int so efficient, they can only represent very specific things. And 00101111 isn't one of them. Only 101111 is.

If you have a need to store such a concept, well, that isn't a number. It's some sort of limited string; use String (in which case you can just invoke str.length() to figure out how many characters are in it), or write your own type for it.

If you are provided an int value and asked to count the digits, and you want an answer of '8' because that int was created with 00101111, that is completely impossible - you'll need to change whatever code gave you that int, and change it to give you a String or some specific other data type instead.

huangapple
  • 本文由 发表于 2023年4月17日 08:20:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76030953.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定