[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].

思路

练手题目,哈哈。不过需要注意特殊情况:1)num < 0;2)num == 0。算法的时间复杂度应该是O(log_{7}n)。其实也就是O(logn),因为以7为底的对数和以2为底的对数是线性关系。

代码

class Solution {
public:
    string convertToBase7(int num) {
        if (num < 0) {
            return "-" + convertToBase7(-num);
        }
        else {
            string ret;
            while (num != 0) {
                ret.push_back(num % 7 + '0');
                num /= 7;
            }
            reverse(ret.begin(), ret.end());
            return ret.length() == 0 ? "0" : ret;
        }
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值