Hexadecimal conversion - Algorithm Notes

Binary converting step:
P-Q-ary to binary conversion requires a two-step

  • The P number is converted to decimal number hexadecimal
  • Decimal conversion of Q-ary
int y =0,product=1;//p进制x转化为10进制的y
while(x!=0){
	y=y+(x%10)*product;//x%10为了取x的个位数
	x=x/10;
	product=product*p;
}

//十进制y转化为Q进制z
int z[40],num=0;//数组z存放Q的进制数y的每一位,num为位数
do{
	z[num++] = y%Q;//除基取余
	y=y/Q;
}while(y!=0);
//这样数组从高位z[num-1]到低位num[0]就正好是Q进制的z。
//这儿用do while而不用while是因为如果y正好为0,用while会让循环直接跳出,结果出错。

Title: PAT 1022 D hex A + B (20 minutes)

Enter two non-negative decimal integers A and B (≤2 30 -1), the output A + B of the D (1 <D≤10) binary number.

Input formats:

A given integer input successively three in a row, B and D.

Output formats:

Output A + D B of the hexadecimal number.

Sample input:

123 456 8

 

Sample output:

1103

answer:

//一刷代码
#include <iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;

int main() {
	long long int a,b,c;
	int d;
	cin>>a>>b>>d;
	c = a+b;
	int v[100];
	int i = 0;
	if(c==0){
		cout<<"0";
		return 0;
	} 
	
	while(c!=0){//有一个测试点通不过,因为少考虑了c = 0的情况 
		v[i] = c%d;
		c = c/d;
		i++;
	}
	for(int j = i-1;j>=0;j--){
		cout<<v[j];
	}
	return 0;
}
//整理思路后的代码

#include<iostream>
using namespace std;
int main(){
    int a,b,c;
    cin>>a>>b>>c;
    a=a+b;
    int z[40],num=0;//z里面存放c进制数的每一位,num表示位数。
    do{
        z[num++]=a%c;
        a/=c;
    }while(a!=0);
    for(int i = num-1;i>=0;i--)//逆序输出就是结果
        cout<<z[i];
    return 0;
}

 

Published 98 original articles · won praise 2 · Views 3703

Guess you like

Origin blog.csdn.net/qq_30377869/article/details/105010380