-2

So this is a code chef question in this we are given a string of binary count we just have to count the zeroes from the last till the first 1 come(start from the last)

I tried to use the function __builtin_ctz and also tried s.size()-s.find_last_of('1')-1 and by a loop just simply by counting the number of zeroes i would like to know why my simple loop code is giving me correct answer and why my all fancy methods are getting me wrong answer in codechef

here are the codes

#include <iostream>
using namespace std;

int main() {
    long int N;
    cin >> N;
    string s;
    cin >> s;
    int count = 0;

    for (long int i = s.size()-1; i>=0; i--)
    {
        if (s[i] =='0')
            count++;
        if (s[i] == '1')
            break;
    }
    cout << count<<endl;
    return 0;
}

Above code is giving correct answer

#include <iostream>
#include<math.h>
using namespace std;
#include<bits/stdc++.h>

int main() {
    long int N;
    cin >> N;
    char s[N+1];
    cin >> s;
    string p =s;
    long int num = strtol(s,NULL,2); 
    cout<<__builtin_ctz(num)<<endl;
    
    return 0;
}

Not giving correct answer

#include <iostream>
#include<math.h>
using namespace std;
#include<bits/stdc++.h>

int main() {
    long int N;
    cin >> N;
    char s[N+1];
    cin >> s;
    string p =s;
    long int num = strtol(s,NULL,2);

    if (num%2 == 1) { cout<<"0\n"; }
    else
    {
        cout<<p.size()-p.find_last_of('1')-1<<endl;
    }
    return 0;
}

when i am trying my test cases that i have figured out all are giving same answer. Can any anone help me find out what is going wrong? here is the link of question https://www.codechef.com/problems/MAX2

sujoybyte
  • 584
  • 4
  • 19

1 Answers1

0

Always remember that C/C++ does not allow for dynamic memory allocation that way.

cin >> N ;
char a[N] ; // this does not work 
// Memory is allocated at compile time and not at runtime.

you might want to allocate the memory at runtime using either a malloc/calloc or a new operator. (and don't forget to free/delete it afterward)