programming problem in C++

I was trying to solve this problem but got stuck.the problem goes like
I have a string of 0's and ones which is to be inputted by the user ..
may be something like "000110010"..The solution is a string in which I get 0's on one side and 1's on other side( like compaction where 0 represents used memory and 1 represents free memory)..+ the total distance (in terms of shifts) ..
For the string: 000110010..the output would be 000000111. and the diatance 1's or 0's have to be moved to achieve the output!
Can anyone help ????


  • pooja sehgal
    pooja sehgal
    plz mention about d distance moved
    we have to specify the distance moved by each 1 or 0 ????
    or the total distance covrd by all 1's & 0's??
  • ankur8819
    It is the total distance moved by all zero's or one's!
  • pradeep_agrawal
    Below is a sample code for above problem statement.

    #include "stdio.h"
    #include "string.h"
    #define MAX_STRING_LEN 100
    int main() {
      char str[MAX_STRING_LEN + 1] = {0};
      int strl = 0;
      int move_count = 0;
      int move_pos = 0;
      int i = 0;
      scanf("%s", str);
      strl = strlen(str);  
      if(strl < 1) {
        printf("Empty string\n");
        return 0;
      for(i = 0; i < strl; i++) {
        if((str[i] != '0') && (str[i] != '1')) {
          printf("Invalid character in string\n");
          return 0;
      for(i = strl -1, move_pos = strl - 1; i >= 0; i--) {
        if(str[i] == '1') {
          str[i] = '0';
          str[move_pos] = '1';
          move_count += move_pos - i;
      printf("Result string: %s\n", str);
      printf("Total movement: %d\n", move_count);
      return 0;
    Compile the file with above code and run as:
    a.exe < input.txt > output.txt [on windows]
    a.out < input.txt > output.txt [on linux]

    a.exe or a.out are the executables generated after compilation
    input.txt is the file containing input string
    output.txt is the output file containing result


You are reading an archived discussion.

Related Posts

what is the principal for vacuume pump?
in my project i require bcd at port 0 and 3 of microcontroller 89s52 since there are three 7447 connected (i.e p0.0-p0.3 to 7447(1) lsb, p0.4-p0.7 to7447(1), p3.0-p3.3 to7447(3)msb) which...
Hello i want the use of delegates especially where exactly they use delegates and how .
i hope it is ok for this forum. may i invite all capricorns to join - it is a forum site for all capricorns. thanks.
i am a crazy CSE student n im in 3rd semester..........😁;-)