in China, number "4" is not good because it is has the same pronunciation as "death" in Chinese. so there is a new number system which we may make 4 disappear in the current decimal system. like: 1,2,3,5,6,7.......13,15.......23,25.......33,35....39,50........
here 5 is 4 in decimal system, and 15 is 13.....
so write a function, input a positive number and output should be like this:
1 -> 1;
2 -> 2;
5 -> 4;
4 -> illegal;
15 -> 13;
int getNUM(int num);
so can anyone give me some specific algorithms or code for this function?
thanks.
分析:
ex 1: 562
if any of the digit is greater than 4 then subtract that digit by 1, so this will become now 455
now convert this number to base 9
9^2*4 + 9^1*5 + 9^0*2
324 + 45 + 2
371
ex 2: 123 (none of the digits are greater than 4, so no need to subtract by 1)
9^2*1 + 9^1*2 + 9^0*3
81 + 18 + 3
102
ex 3: 456
any of the digits contains 4 then return -1 as this is illegal
#include <cstdlib>
#include <string> // for c++ string class
#include <fstream>
#include <sstream>
#include <iomanip>
#include <iostream>
#include <cstring> // for c str: strcmp,strcat
#include <cassert> // for assert()
#include <climits> // for INT_MIN, INT_MAX;
using namespace std;
int ConvertNum(int n)
{
int i,j;
int res = 0;
for (i = n, j = 1; i > 0; i = i / 10)
{
int d = i % 10;
if (d == 4)
{
cerr << "Illegal input!" << endl;
return -1;
}
res += (d > 4) ? (d-1)*j : d*j;
j *= 9;
}
return res;
}
int main ( int argc, char *argv[] )
{
cout << ConvertNum(562) << endl;
return 0;
} // ---------- end of function main ----------
945



被折叠的 条评论
为什么被折叠?



