leetcode-504-Base 7

Posted chenjx85

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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。

以上是关于leetcode-504-Base 7的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段7——CSS动画

VSCode自定义代码片段7——CSS动画

ES7-Es8 js代码片段

以下代码片段的时间复杂度是多少?

vscode代码片段建议bug

Notepad++编辑器——Verilog代码片段直接编译