leetcode 504. Base 7(easy)

来源:互联网 发布:京东和淘宝联盟类似 编辑:程序博客网 时间:2024/06/06 17:46

Given an integer, return its base 7 string representation.

Example 1:

Input: 100Output: "202"

Example 2:

Input: -7Output: "-10"

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

题目是要将10进制转换成7进制,但是需要注意这里是转换成string,同时需要注意负数和0的处理。

class Solution {public:    string convertToBase7(int num) {        //转换成7机制,那么就连续除以7        string result;        if(num == 0) {result = '0'; return result;}        int flag = 0;        if(num<0)         {            num = -num;            flag = 1;        }        while(num != 0)        {            int a = num%7;            num = num/7;            stringstream ss;            ss<<a;            result = ss.str() + result;        }        if(flag == 1) result = "-"+result;        return result;    }};


0 0
原创粉丝点击