天池在线编程 2020国庆八天乐 - 7 进制

文章目录

1. 题目

https://tianchi.aliyun.com/oj/118289365933779217/122647324212270017

Given an integer, return its base 7 string representation.

输入范围为[-1e7, 1e7] 。

示例
样例 1:
输入: num = 100
输出: 202

样例 2:
输入: num = -7
输出: -10

2. 解题

  • 除以base得到余数,对所有的余数逆序
class Solution {
    
    
public:
    /**
     * @param num: the given number
     * @return: The base 7 string representation
     */
    string convertToBase7(int num) {
    
    
        // Write your code here
        bool negative = num < 0;
        if(negative)
        	num = -num;
        string ans;
        int base = 7;
        do
        {
    
    
        	ans += (num%base)+'0';
        	num /= base;
        }while(num);
        reverse(ans.begin(), ans.end());
        if(negative)
        	ans = "-"+ans;
        return ans;
    }
};

我的CSDN博客地址 https://michael.blog.csdn.net/

长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!
Michael阿明

猜你喜欢

转载自blog.csdn.net/qq_21201267/article/details/108895186