C ++ returns Integers

Source: Internet
Author: User

Set the input positive integer to obtain the numbers.

Method 1:

Note:

The default value is 9 bits. For example, if the input is 123, the output (from a single bit to a higher position) is 3 2 1 0 0 0 0 0 0, that is, the output is 0 at a higher position.

 

The Code is as follows:

# Include <iostream> using namespace STD; const long a [] = {10,100,100 1000000000, 10000, 100000,000000, 0000000,00000000,}; int main () {long num; int digits, I; while (CIN> num) {for (I = 0; I <9; I ++) {digits = (Num % A [I]) /(A [I]/10); // key cout <digits <"" ;}cout <Endl ;}return 0 ;}

Test instance:

Method 2:

# Include <iostream> using namespace STD; const int P = 10; // note int main () {int N, D; while (CIN> N) {While (n! = 0) {d = n % P; cout <D <""; N/= P;} cout <Endl;} return 0 ;}

The second method is a little cheaper than the first method, and it is easier to understand without the need to open arrays. Note the comments in the code. If you change the value of P, for example, to 2, the code is converted from decimal to binary.

Note: ① the output number ranges from low to high from left to right. For example, if p = 2 and input 4, the output is 0 0 1. ② When P is greater than 10, some bits are represented by a B c... and are not given in the code.

 

Method 3:

Strictly speaking, this method cannot obtain all the digits of an integer, but can easily obtain the total number of digits of an integer. So, paste it here!

The Code is as follows:

#include<iostream>#include<cmath>using namespace std;int main(){int n;while(cin>>n){double dig=log10(n);cout<<int(dig)+1<<endl;}return 0;}

Analysis: if the number of digits of integer a is N, there must be 10 ^ n-1 <= A <10 ^ n. So n = int (lg (A) + 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.