سؤال

How to find most popular digit inside the number. for example I have number 222244, the most occurring digit is 2. Please help.

I have something like this, but don't really understand this first part of method, what is going on with int j = liczba.charAt(i) - 47; why 47 is here? anyone can explain it?

int digits[] = new int [10];         
for(int i = 0; i <liczba.length(); i++){
    int j = liczba.charAt(i) - 47;
    digits[j]++;
}

int digit = 0; 
int count = digits[0];
for(int i=1;i <10; i++){
    if(digits[i] >count){
        count = digits[i];
        digit = i;
    }
}
return digit;
هل كانت مفيدة؟

المحلول

The line

int j = liczba.charAt(i) - 47;

Subtracts the character code of (i+1)th character liczba by 47. Refering to an ASCII table, 47 maps to "/", whose ASCII code is one less than "0".

Note that I am assuming the following, as your code appears to be in Java.

  • String indexes starts at zero i.e. first character has index 0, second character has index 1, and so on
  • It seems that characters and integers can be used interchangeably, because a character is internally represented by an integer, namely, the ASCII code of the character.
  • That said, the char type is actually an integer type, with less range

Hence, this code is to turn characters "0" to the integer 1, "1" to the integer 2, etc.

For example, when the 1st character (liczba.charAt(0)) is the character 0, liczba.charAt(0) returns character '0', which is also equals to number 48 -- because '0' has an ASCII code of 48.

Subtracts 48 with 47 gets 1, so it would convert character '0' to integer 1.

However it seems that this code could cause array index out of bounds error (assuming zero-based array indexes). when a digit is '9', this line returns 10. This would cause an aforementioned error. Unless this code's language's array are 1-based. However, even in this case, this line

int count = digits[0];

would simply fail. This code seems to fail with the common Off by one error

I believe this line should actually read

int j = liczba.charAt(i) - 48;

so that character '0' is converted to number 0.

If this still disturb you, you may change this line to

int j = liczba.charAt(i) - '0';

so it would be clearer. Subtract the code of '1' and the code of '0' gets you the integer 1, clear enough :)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top