Converts a decimal number to a binary number----no arrays, no functions, only loops

Source: Internet
Author: User

Enter a positive integer (decimal) to output the binary number corresponding to this integer (implemented in a loop, but without an array or function call)

/*Enter a positive integer (decimal), output this integer corresponding to the binary number (with the loop implementation, but not the array) analysis: decimal conversion to binary mode: by the number of the Division in order to take the remainder, until the quotient is 0, to obtain the inverse of the residue sequence is the corresponding binary number with the loop without the array, therefore, will be first A sequence of integers that consists of an integer value, which is then output in reverse order (from low to high output), which is the binary code*/#include<iostream>using namespacestd;intMain () {intN//decimal positive integer to be converted    intM//the remainder of the save per conversion    intsum=0;//binary conversion Inverse value    intCount=0;//record number of bits    inti; cout<<"Please enter the decimal positive integer to be converted:"; CIN>>N;  while(n<0) {cout<<"Please re-enter the decimal positive integer to be converted:"; CIN>>N; } cout<<Endl; cout<<"decimal"<<n<<"The binary form is:"; if(n==0) {cout<<n<<Endl; return 0; }     while(n!=0)//The division takes the remainder to the quotient is 0{m=n%2;//get the remainder corresponding to thiscount++;//bits number increased by 1sum=sum*Ten+m;//The remainder consists of an integer in the first order, and the last inverse is the 2 binary numbern=n/2; }     for(i=count;i>0; i--)//loop from low to high reverse output sum of the digits on each bit{cout<<sum%Ten; Sum=sum/Ten; } cout<<Endl; return 0;} 

Converts a decimal number to a binary number----no arrays, no functions, only loops

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.