Advertisement

Simple Simple Simple C++

Started by August 20, 2000 05:59 AM
6 comments, last by Virus 24 years, 4 months ago
I''ve been trying to write a console program that takes an unsigned interger and returns how many 1''s are in its binary representation. void main (void) { unsigned int counter=0; int unsigned number; cin>>number; for ( unsigned int j =1; j 0; j=j/2) { if ( ( j < number ) && ( (number-j)%2)) counter++; } cout<<endl; cout<<"There are "<< counter <<" ones in "<<number <<"binary"<<endl; ; } WHATS WRONG WITH THIS? Gladiator told me to do this................ A hint, yes. Okay, here''s what you''d do: #ifdef WINDOWS #define NUMBER_OF_BITS 32 #else #define NUMBER_OF_BITS 16 #endif counter = 0 for i = 0 to NUMBER_OF_BITS-1 if input_number AND 2^i then counter = counter + 1 goto for Now counter contains the number of 1''s that you have in input_number. Hope this helps you some! ------------------------------- That''s just my 200 bucks'' worth! ..-=gLaDiAtOr=-.. but it didn''t work either..... for (int i = 0; i < NUMBER_OF_BITS-1; i++ ) { if ( number && 2^i) counter = counter + 1; } ANY help will be appreciated! maybe i misunderstood the pseudo! ||||-- Our creation is the transformation of one. --|||
||||-- Our creation is the transformation of one. --|||
What you should do is to get the number and use _itoa to convert it to a string using base 2 (see MSDN documentation for help on _itoa). Then, use a loop to just step through the string that you have just got, and each time you hit a 1, increment a counter.
Advertisement
Thank you, i''ll try it right now.

||||-- Our creation is the transformation of one. --|||
||||-- Our creation is the transformation of one. --|||
The reason the below code didn''t work is because of the &&, it should have been &.

for (int i = 0; i < NUMBER_OF_BITS-1; i++ )
{
if ( number && 2^i)
counter = counter + 1;
}

Also, my code for this is (which should be ALOT faster than the itoa method:

for (int i=NUMBER_OF_BITS;i;i--)
{
if (number&1) counter++;
counter=counter>>1;
}

Greetings,
FReY
do unto others... and then run like hell.
Ooops, MY code above should be

for (int i=NUMBER_OF_BITS;i;i--)
{
if (number&1) counter++;
number=number>>1;
}

It should be number=number>>1 and not counter=counter>>1

Hope I''ve helped,
FReY
do unto others... and then run like hell.
YES IT WORKED... thank you Frey!

||||-- Our creation is the transformation of one. --|||
||||-- Our creation is the transformation of one. --|||
Advertisement
<table width=200>
<tr><td BGCOLOR="#FFFFFF">This should be it</td></tr></table>
[table width=200]
[TR][TD BGCOLOR="#FFFFFF"]This should be it[/TD][/TR][/TABLE]

This topic is closed to new replies.

Advertisement