1

Given two numbers. I want to compare the two numbers positional notations.

Say number 1 is: 25000 Say number 2 is: 25000

And the result is the mask. If each positions match, then the mask (in this case) is: 6

Say number 1 is: 00000 Say number 2 is: 22220

Then the mask is 1, because only the first bit matches.

My logic was, if the length of the two numbers aren't equal, then it prints that it isn't equal, and does nothing. But if they match, then I convert them to integers. And after that, I check with 2 for loops if their respective numbers are equal. If they are, then I add one to the maszk variable.

My code is wrong below (I have already entered the headers and declared the variables and the getline.) Can anyone help?

#include <stdio.h>
if( strlen(s) != strlen(s2) ) printf("The length doesn't match! \n");


else {


for(i=0; i<=20; i++)
{

 for(j=0; j<=20; j++)
    {
    szam1[i] = atoi(s);
    szam2[j] = atoi(s2);

    }
  if( szam1[i] == szam2[j] ) maszk++;

}
}

printf("The mask of the two numbers: %d", mask);

}
  • keep the number as a string, use `charAt()` starting from the end of both strings and update `mask` till the condition is true. you don't need two for loops for this. – Swastik Padhi Oct 23 '15 at 12:28
  • I'm unclear why the result is 6 in the first example (complete agreement). There are after all only five characters in the (decimal) representations. In the second example you have result 1 where the only agreement is in the first place (units digits). – hardmath Oct 23 '15 at 12:28

1 Answers1

0

I don't know where your bug is, but I thought up this algorithm--might be simpler:

Given two numbers A and B...
m = max(digits(A), digits(B))
maxMask = m + 1
s = A-B 
if (s == 0)
    mask = maxMask
else
    mask = 0
    loop m times
      if (s % 10 == 0)
        mask++
        s /= 10
      else
        break

That is, subtract them. If the result is zero, the mask is 1 + the greatest number of digits. If not, the mask is however many trailing zero's the result has.

Also, you might consider renaming that variable. "mask" is frequently used to mean something else.

Community
  • 1
  • 1
MatrixManAtYrService
  • 8,023
  • 1
  • 50
  • 61