Skip to content

504. Base 7

  • Time: $O(\log_7 n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
 public:
  string convertToBase7(int num) {
    if (num < 0)
      return "-" + convertToBase7(-num);
    if (num < 7)
      return to_string(num);
    return convertToBase7(num / 7) + to_string(num % 7);
  }
};
1
2
3
4
5
6
7
8
9
class Solution {
  public String convertToBase7(int num) {
    if (num < 0)
      return "-" + convertToBase7(-num);
    if (num < 7)
      return String.valueOf(num);
    return convertToBase7(num / 7) + String.valueOf(num % 7);
  }
}