例題(12.9) 數制轉換,例題12.9數制轉換

來源:互聯網
上載者:User

例題(12.9) 數制轉換,例題12.9數制轉換

描述
求任意兩個不同進位非負整數的轉換(2進位~36進位),所給整數在long所能表達的範圍之內。 
不同進位的表示符號為(0,1,...,9,a,b,...,z)或者(0,1,...,9,A,B,...,Z)。
關於輸入
輸入只有一行,包含三個整數a,n,b。a表示其後的n 是a進位整數,b表示欲將a進位整數n轉換成b進位整數。 a,b是十進位整數,2 ≤ a,b < 36。
關於輸出
輸出包含一行,該行有一個整數為轉換後的b進位數。輸出時字母符號全部用大寫表示,即(0,1,...,9,A,B,...,Z)。
例子輸入
15 Aab3 7
例子輸出
210306
提示
可以用字串表示不同進位的整數

#include <stdio.h>char symbol[256];/* 數對應的符號 */int value[256];/* 符號代表的數 */void setup(){int j;for (j = 0; j < 10; ++j){symbol[j] = '0' + j;value['0' + j] = j;}for (j = 10; j < 36; ++j){symbol[j] = 'A' + j - 10;value['A' + j - 10] = j;value['a' + j - 10] = j;}}long from_base(char *n, int a){long x = 0;while (*n){x = a * x + value[*n];n++;}return x;}char *to_base(long x, char *s, int b){do{*(--s) = symbol[x%b];x = x / b;} while (x);return s;}int main(){int a = 0, b = 0;char n[256] = { 0 };long x = 0;char *p = 0;scanf("%d %s %d", &a, n, &b);setup();x = from_base(n, a);p = to_base(x, n + 255, b);printf("%s\n", p);return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.