Shredded Code: Analyzing binary string is divided by 3

Subject description:

Given a binary string length, find the remainder after division by 3 is

 

Analysis of ideas:

Here it comes to the state machine, because the remainder of the division three can only be 0,1,2. So there are three state machine state. Now one by one to traverse a binary string, the initial remainder is 0, when faced with 1:00, go to the state 1, the state is still experiencing 0:00 0. For state 1, state 0 is determined and were encountered converting the 1: 0 encountered, i.e., a remainder of 2 to state 2; 1 encountered, i.e., the remainder is 0 to state 0. It can be found, for each number 0 corresponds added thereafter by 2, by adding 1 equivalent of 1 plus 2.

 

Code:

 1 int numRest(string s)
 2 {
 3     int n = s.length();
 4     int res=0;
 5     for(int i=0; i<n; i++)
 6     {
 7         if(res==0)
 8         {
 9             if(s[i]=='0')
10                 res=0;
11             else
12                 res=1;
13         }
14         else if(res==1)
15         {
16             if(s[i]=='0')
17                 res = 2;
18             else
19                 res=0;
20         }
21         else
22         {
23             if(s[i]=='0')
24                 res=1;
25             else
26                 res=2;
27         }
28     }
29     return res;
30 }

 

Guess you like

Origin www.cnblogs.com/LJ-LJ/p/11610433.html