10進数整数をb進数文字列に変換する(再帰的および非再帰的実装)
10進数整数nをb進数に変換した後、文字列からsに変換する
すなわち、IntoString(int n,char*s,int b)関数を実現する.
ここでは、再帰と非再帰の2つの方法で実現され、以下はc++ソースコードである.
すなわち、IntoString(int n,char*s,int b)関数を実現する.
ここでは、再帰と非再帰の2つの方法で実現され、以下はc++ソースコードである.
#include <iostream>
#include <string.h>
using namespace std;
// intToString
/*
* : n b , s
* :n ,
* s
* b
*/
void intToString_Recursion(__int64 n, char* s, int b)
{
// i
// n >= 0 , :1 、 n 0, s = "0" ( '\0')
// 2 、i = 0, s 0
// n < 0 , : 1 、 '-';
// 2 、n ;
// 3 、i = 1, s 1
static int i = (n >= 0 ? (s[0] = '0', s[1] = '\0' ,0) : (s[0] = '-', n = -n, 1) );
static char bChar[16] = // ( , )
{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
if(n != 0)
{
intToString_Recursion(n/b, s , b); // ,
s[i++] = bChar[n%b]; //
s[i] = '\0'; // '\0', '\0',
}
}
// intToString
/*
* : n b , s
* :n ,
* s
* b
*/
void intToString_NonRecursion(__int64 n, char* s, int b)
{
static char bChar[16] = // ( , )
{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
int i = 0;
if(0 == n)
{ //n = 0:
s[0] = '0'; // s = "0"
s[1] = '\0';
return; //
}
else if(n < 0)
{ //n < 0: ,
s[0] = '-'; // '-'
n = -n; //
i = 1; // i = 1, i
}
while(0 != n)
{ // b
s[i++] = bChar[n%b];
n = n / b;
}
s[i] = '\0';
int high = strlen(s) - 1;
int low = s[0] == '-' ? 1 : 0; // '-'
while(low < high)
{ //
char t = s[low];
s[low] = s[high];
s[high] = t;
low++;
high--;
}
}
int main()
{
char s[50];
char s1[50];
intToString_Recursion(-12345678999999, s , 2); //
intToString_NonRecursion(-12345678999999, s1, 2);//
cout<<s<<endl;
cout<<s1<<endl;
return 0;
}