| 7 | //function that takes in String and returns an int |
| 8 | |
| 9 | int solution(char *S) { |
| 10 | |
| 11 | //we store the length of string S in N |
| 12 | |
| 13 | int N=strlen(S); |
| 14 | |
| 15 | int count=0, number=0,bit=0,j=0; |
| 16 | |
| 17 | //traversing S from the end |
| 18 | |
| 19 | for(int i=N-1;i>=0;i--) { |
| 20 | |
| 21 | //convert S[i] to integer |
| 22 | |
| 23 | bit=S[i]-'0'; |
| 24 | |
| 25 | //converting binary to decimal form |
| 26 | |
| 27 | number = number + (pow(2,j) * bit); |
| 28 | |
| 29 | //increasing power of 2 as we move from right to left |
| 30 | |
| 31 | j++; |
| 32 | |
| 33 | } |
| 34 | |
| 35 | //while the number is greater than 0 |
| 36 | |
| 37 | while(number>0) { |
| 38 | |
| 39 | //if number is even |
| 40 | |
| 41 | if(number%2==0) { |
| 42 | |
| 43 | //divide it by 2 |
| 44 | |
| 45 | number=number/2; |
| 46 | |
| 47 | } |
| 48 | |
| 49 | //if number is odd |
| 50 | |
| 51 | else |
| 52 | |
| 53 | //decrement it by 1 |
| 54 | |
| 55 | number = number -1; |
| 56 | |
| 57 | //increment count in every iteration |
| 58 | |
| 59 | count++; |
| 60 | |
| 61 | } |
| 62 | |
| 63 | //returning count |
| 64 | |
| 65 | return count; |
| 66 | |