?LeetCode刷題實戰(zhàn)504:七進制數(shù)
Given an integer?
num, return?a string of its?base 7?representation.
示例? ? ? ? ? ? ? ? ? ? ? ? ?
示例 1:
輸入: num = 100
輸出: "202"
示例 2:
輸入: num = -7
輸出: "-10"
解題

class?Solution?{
public:
????string?convertToBase7(int?num)?{
??????if(num == 0)
????????return?"0";
????????bool?negative = (num < 0);
????????num = abs(num);
????????string?ans;
????????while(num)
????????{
??????????ans.append(to_string(num%7));//余數(shù)
??????????num /= 7;
????????}
????????if(negative)
??????????ans.push_back('-');
????????reverse(ans.begin(), ans.end());//逆序
????????return?ans;
????}
};
評論
圖片
表情
