google面试题9

->it is asked by my friend.
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  ---------- 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值