XM7. 进制间转换
描述
设计一个函数, 可以将任意十进制的数, 转换成任意2到9的进制表示的形式输入描述
需要转换的数字x(0<=x<=1e18) 转换使用的进制k(2<=k<=9)输出描述
对应进制的结果示例1
输入:
33 2
输出:
100001
C 解法, 执行用时: 1ms, 内存消耗: 380KB, 提交时间: 2020-08-08
/* 将十进制数转换为2~9进制,十进制范围(0~1e18) 输入: 33 2 输出:100001 */ #include <stdio.h> /* 编译时链接 -lm */ #include <math.h> void DecimalTurn (unsigned long long DecimalNum, unsigned int n) { int i = 0; unsigned long long k = 0; unsigned int TurnResult[64] = {}; do { TurnResult[i] = DecimalNum % n; DecimalNum = DecimalNum / n; i++; }while (0 != DecimalNum); for(i--; i >= 0; i--) { printf("%d", TurnResult[i]); } printf("\n"); return; } int main () { unsigned long long DecimalNum = 0; unsigned int n = 0; scanf("%lld %d", &DecimalNum, &n); DecimalTurn(DecimalNum, n); return 0; }
C 解法, 执行用时: 1ms, 内存消耗: 432KB, 提交时间: 2020-08-21
#include<stdio.h> int main() { long long int data; int format; scanf("%lld %d",&data,&format); int temp; char output[20000]={0}; int count = 0; do { temp = data%format; data = data/format; output[count++] = temp; }while(data != 0); count--; for(;count>=0;count--) { printf("%d",output[count]); } return 0; }
C++14 解法, 执行用时: 1ms, 内存消耗: 492KB, 提交时间: 2020-05-20
#include <stdio.h> #include <stdlib.h> using namespace std; //思路和步骤是,找到运算核心和合适的数据结构。运算核心:相除取余。数据结构:双向链表。要注意不要让技术问题成为思路实现的障碍 struct yu_store { yu_store* front; int a; yu_store* next; }; int main() { long int num; long int yu = 1; int n; int count; yu_store* f; yu_store* p; yu_store* s; scanf("%ld",&num); getchar(); scanf("%d",&n); p = (yu_store *)malloc(sizeof(yu_store)); f = p; f->front = NULL; f->next = NULL; if(num == 0) { printf("%ld",num); return 0; } while(num != 0) { yu = num%n; num = num/n; s = (yu_store *)malloc(sizeof(yu_store)); p->a = yu; p->next = s; s->front = p; s->next = NULL; p = s; } while(f != p) { p = p->front; printf("%d",p->a); free(s); s = p; } free(f); return 0; }
C++14 解法, 执行用时: 2ms, 内存消耗: 368KB, 提交时间: 2020-05-12
#include <stdio.h> #include <stdlib.h> using namespace std; //思路和步骤是,找到运算核心和合适的数据结构。运算核心:相除取余。数据结构:双向链表。要注意不要让技术问题成为思路实现的障碍 struct yu_store { yu_store* front; int a; yu_store* next; }; int main() { long int num; long int yu = 1; int n; int count; yu_store* f; yu_store* p; yu_store* s; scanf("%ld",&num); getchar(); scanf("%d",&n); p = (yu_store *)malloc(sizeof(yu_store)); f = p; f->front = NULL; f->next = NULL; if(num == 0) { printf("%ld",num); return 0; } while(num != 0) { yu = num%n; num = num/n; s = (yu_store *)malloc(sizeof(yu_store)); p->a = yu; p->next = s; s->front = p; s->next = NULL; p = s; } while(f != p) { p = p->front; printf("%d",p->a); free(s); s = p; } free(f); return 0; }
C 解法, 执行用时: 2ms, 内存消耗: 372KB, 提交时间: 2020-08-11
#include <stdio.h> int main() { unsigned long long x; int k; int j = 0; char delta = '0'; char a[100] = {'0'}; scanf("%lld %d", &x, &k); if(k <= 1 || k > 10) return -1; while(x > 0) { a[j++] = x%k + delta; x /= k; } if(j == 0) { printf("0"); return 0; } for(k = j -1; k >= 0; k--) { printf("%c", a[k]); } return 0; }