Skip to main content
Back to problems
#504
Easy Algorithms

Base 7

Math String
53.8% acceptance
Feb 19, 2026
885
239
Given an integer num, return a string of its base 7 representation.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn convert_to_base7(num: i32) -> String {
    if num == 0 {
      return "0".to_string();
    }
    let negative = num < 0;
    let mut n = num.abs();
    let mut digits: Vec<u8> = Vec::new();
    while n > 0 {
      digits.push((n % 7) as u8 + b'0');
      n /= 7;
    }
    if negative {
      digits.push(b'-');
    }
    digits.reverse();
    String::from_utf8(digits).unwrap()
  }
}