The most obvious problem is that you're testing for 0 or 1 instead of '0' or '1'. Remember the the contents of your string are characters, not integers. You're also going about the problem in a complicated way, but because you don't want help with that part, I won't show you a simpler solution.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>Can you write down the idea of the other way?
Look carefully at the data. You have a 1 followed by 0's, then another 1 and the same amount of 0's. If you count the 0's then you'll see that it's N + 1 where N is the size of the matrix (ie. NxN, or 3x3).
To verify that the matrix is valid, you need all 0's except for the first, and every (N + 1)st beyond that. Those values must be 1. This gives you an immediate solution for counting the 1's:
size_t len = strlen ( s );
for ( i = 0; i < len; i += N + 1 ) {
if ( s[i] != '1' )
invalid();
}
Now the only problem is making sure that the other values are all 0. The simplest way to do this is a trivial loop:
for ( i = 0; i < len; i++ ) {
if ( s[i] != '0' )
invalid();
}
But because there are 1's, that won't work unless you make sure that the 1's won't be counted, or won't make a difference if they are. You're probably ahead of me by now, but consider this:
size_t len = strlen ( s );
for ( i = 0; i < len; i += N + 1 ) {
if ( s[i] != '1' )
invalid();
s[i] = '0'; // Turn a 1 into a 0
}
for ( i = 0; i < len; i++ ) {
if ( s[i] != '0' )
invalid();
}
This solution is easy to understand, easy to verify, and has linear complexity.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401