Since you said "string", I'll add the following technique:
Note that if you append 0
at the end of a binary number, you double it's value. If you append 1
at the end, you double it and add 1.
That is, if you have processed all digits up to a certain digit (call this number up to that digit a
), and you know that a % 3 = x
for some x=1, 2 or 0
, then you can tell the following:
a0 % 3 = (2 * a) % 3 = ((2 % 3) * (a % 3)) % 3 = (2 * (a % 3)) % 3
a1 % 3 = (2 * a + 1) % 3 = ((2 % 3) * (a % 3) + (1 % 3)) % 3 = (2 * (a % 3) + 1) % 3
This way, you can easily make the following distinction:
Current mod | Next digit | New mod
------------+------------+---------
0 0 0
0 1 1
1 0 2
1 1 0
2 0 1
2 1 2
That is, you can traverse your string from left to right (assuming msbf notation) and update the new mod
according to the table. You start with current mod = 0
.