Write a function to return the number of 1 in the parameter binary example: 15 0000 1111 4 1

Source: Internet
Author: User

Method One: Program: #include <stdio.h>int count_one_bits (int t) {int i = 32;int count = 0;while (i>0) {if (t & 1 = = 1) {count ++;} t=t/2t = t >> 1;i-= 1;} return count;} int main () {int t = 0;printf ("Please enter an integer:"), scanf ("%d", &t), int ret=count_one_bits (t);p rintf ("count=%d\n", ret); return 0;} Method Two: Program: #include <stdio.h>int count_one_bits (int t) {int count = 0;while (t) {count++;t = t& (t-1);//The lowest bit is 1, the remainder is all 0, The cycle efficiency is high, there are several 1 cycles several times}return count;} int main () {int t = 0;printf ("Please enter an integer:"), scanf ("%d", &t), int ret=count_one_bits (t);p rintf ("count=%d\n", ret); return 0;} Result one: Please enter an integer: 15count=4 please press any key to continue ... Result two: Please enter an integer: -2count=31 please press any key to continue ...


This article is from the "Rock Owl" blog, please be sure to keep this source http://10742111.blog.51cto.com/10732111/1717837

Write a function to return the number of 1 in the parameter binary example: 15 0000 1111 4 1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.