doubt in a question of chakpak written test

4 views
Skip to first unread message

gaurav kejriwal

unread,
Nov 22, 2009, 1:27:13 PM11/22/09
to ds--al...@googlegroups.com
Hi,
There was question in the written test of chakpak to depict what the
following piece of code is doing.Somebody plz give the solution.

int main()
{
int n;
scanf("%d",&n);
printf("%d",getval(n));
return 0;
}

int getval(int n)
{if(n==0)
return 0;
else
{
int temp=getval(n&n-1);
temp++;
return temp;
}
}

most probably the code was this.if it is wrong,somebody who appeared
in the test plz correct it.

Thanks
Gaurav

Ajay

unread,
Nov 22, 2009, 10:02:25 PM11/22/09
to ds--al...@googlegroups.com
I think its calculating the number of bits set in the number.
--
Ajay Kr. Gautam
IDD, Part V
Dept. of Computer Science & Engg., IT-BHU
Varanasi-221005, UP
India

Vipul Agrawal

unread,
Nov 22, 2009, 10:28:44 PM11/22/09
to ds--al...@googlegroups.com
it calculates  total number of 1's in n.
--
VIPUL AGRAWAL
IDD IV Yr. , Department of Computer Science & Engineering
IT BHU , Varanasi
Contacts
Phone No: +919795686718
e-mail :
vipul.agr...@itbhu.ac.in
vipul....@gmail.com

Neeraj Singh

unread,
Nov 22, 2009, 11:15:52 PM11/22/09
to ds--al...@googlegroups.com
On Mon, Nov 23, 2009 at 8:58 AM, Vipul Agrawal <vipul....@gmail.com> wrote:
it calculates  total number of 1's in n.


On Sun, Nov 22, 2009 at 7:02 PM, Ajay <ajay....@gmail.com> wrote:
I think its calculating the number of bits set in the number.


On Sun, Nov 22, 2009 at 11:57 PM, gaurav kejriwal <gaur...@gmail.com> wrote:

Hi,
There was question in the written test of chakpak to depict what the
following piece of code is doing.Somebody plz give the solution.

int main()
{
int n;
scanf("%d",&n);
printf("%d",getval(n));
return 0;
}

int getval(int n)
{if(n==0)
return 0;
else
{
int temp=getval(n&n-1);
temp++;
return temp;
}
}
   
most probably the code was this.if it is wrong,somebody who appeared
in the test plz correct it.

Thanks
Gaurav




n &= n - 1;  clears the least significant bit set.
This code is clearing set bits recursively until there are no set bits.
so finally it returns count of set bits.

A detailed explanation and other better ways to do the same can be found here 

P.S : The link may not open using cc proxy coz of some issues of the cache with this site.




--
Ajay Kr. Gautam
IDD, Part V
Dept. of Computer Science & Engg., IT-BHU
Varanasi-221005, UP
India






--
VIPUL AGRAWAL
IDD IV Yr. , Department of Computer Science & Engineering
IT BHU , Varanasi
Contacts
Phone No: +919795686718
e-mail :
vipul.agr...@itbhu.ac.in
vipul....@gmail.com






--
Neeraj Kumar
B.Tech (4th year)
Department of Computer Sc. & Engineering
IT-BHU,Varanasi
Pablo Picasso  - "Computers are useless. They can only give you answers."
Reply all
Reply to author
Forward
0 new messages