Consider an integer in which each digit is either 0 or 1. Write a program to rearrange the digits such that all the 0s appear before the 1s. Output the resulting number.
sample input: 01001010101 sample output: 00000011111
This is a discussion on Coding help for C programming within the C Programming forums, part of the General Programming Boards category; Consider an integer in which each digit is either 0 or 1. Write a program to rearrange the digits such ...
Consider an integer in which each digit is either 0 or 1. Write a program to rearrange the digits such that all the 0s appear before the 1s. Output the resulting number.
sample input: 01001010101 sample output: 00000011111
Announcements - General Programming Boards
Post some code, don't just dump your assignment on us.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
A way-out for this is to convert your integer to array or string and then compare its elements ( directly if array or on basis of ASCII value if string)
Though there may be some better way-out too... I am a new learner too
You could probably do this with a counting sort as expressed by this "pseudo"code:
Code:for (i = 0; i < len; i++) if (string[i] == '0') num_0++; for (i = 0; i < num_0; i++) output[i] = '0'; for (; i < len; i++) output[i] = '1';
Do yourself a big favor and don't even look at any solution for this, until you've really WORKED to solve it yourself. Solving little puzzles like this is part and parcel to what programming is all about. Instead of looking to others for help, right away, see what you can figure out, using just paper and pen. Ask yourself "How would I do this?"
Now take the answer to that, and see if you can figure out how to simplify it down to small steps, that the computer could use for it's program logic.
FYI: integers never begin with zeroes as their leftmost digit! If you want integers with left most digits, you should think about using a char array with digits. Char array's with digits can have all the zeroes you want (one per array index), anywhere you want, within the char array.
With practice, your ability to solve problems will expand dramatically.
And, Welcome to the forum, sumedh!
Last edited by Adak; 08-19-2012 at 08:53 PM.
If this was to be done in binary then I'd just use the popcount intrinsic followed by table lookup. That's barely 3 lines of code. But I'm guessing that is not what they want here.
You must give more details and/or post an attempt of solving it yourself.
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"