c ++ binary conversion

Title Description

About the integer N converted from decimal to binary R, ​​we are used to is the way "except to take down more than R", this method requires repeated operation with the R division is N, and the remainder of each record in the division operation when done Finally, in reverse order output. In fact, with regard to binary conversion, solving recursive method will be more concise, how do you know what?

Entry

Two positive integers N, R. 1 <= N <= 10000,2 <= R <= 10.

Export

Seeking decimal recursive method results into N R hexadecimal.

Sample input

52 2

Sample Output

110100

prompt

Source Code

#include <iostream>
using namespace std;
int main()
{
    long n;
    int p,c,m=0,s[100];
    cin >> n;//n是要转换的数 (有可能很长) 
    cin >> p;//p是进制数 
    while (n != 0)//当n被取完时退出循环 
    {
        c = n % p;//c是分离出来此进制的第一位
        n = n / p;//对2取整
        m ++;//转换后一共有几位 
        s[m] = c;//把转换后的单个位放到数组里面 
    }
    for(int k = m;k >= 1;k --)//按格式输出 
    {
        if(s[k] >= 10)
            cout << (char)(s[k]+55);
        else        
            cout << s[k];
    }
    cout << endl;
    return 0;
}

Guess you like

Origin www.cnblogs.com/LJA001162/p/11334870.html