Problem
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].
Solution: Simulation
Time complexity: O(logn)
Space complexity: O(logn)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Author: Huahua // Running time: 4 ms class Solution { public: string convertToBase7(int num) { bool is_nagetive = num<0; num = abs(num); string ans; do { ans += ('0' + (num % 7)); num /= 7; } while (num > 0); if (is_nagetive) ans += "-"; reverse(begin(ans), end(ans)); return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment