leetcode-504-Base 7

题目描述:

Given an integer, return its base 7 string representation.

Example 1:

Input: 100
Output: "202"

 

Example 2:

Input: -7
Output: "-10"

 

Note: The input will be in range of [-1e7, 1e7].

 

要完成的函数:

string convertToBase7(int num) 

 

说明:

这道题目要将十进制转化为七进制,熟悉了传统的手工算法,计算机算法就模拟一下手工的方法就好了。要注意的就是num为负值,或者num==0的边界条件。

代码如下:

    string convertToBase7(int num) 
    {
        char t;
        string res="";
        if(num==0)//边界条件的处理
            return "0";
        if(num<0)
        {
            num=-num;
            while(num!=0)
            {
                t=num%7+'0';//将int转化为char类型
                res=t+res;//把新得到的余数放前面
                num/=7;
            }
            res='-'+res;
        }       
        else
        {
            while(num!=0)
            {
                t=num%7+'0';
                res=t+res;
                num/=7;
            }
        }
        return res;
    }

代码十分简洁,实测7ms,beats 79.27% of cpp submissions。

原文地址:https://www.cnblogs.com/chenjx85/p/8971123.html