码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-504-Base 7

时间:2018-04-29 16:29:07      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:example   represent   lse   else   转化   简洁   out   说明   while   

题目描述:

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

标签:example   represent   lse   else   转化   简洁   out   说明   while   

原文地址:https://www.cnblogs.com/king-3/p/8971123.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!