Recursion - Easy Level - Question 1
Leetcode 504 Base 7
Given an integer num, return a string of its base 7 representation.
Constraints:
-10^7 <= num <= 10^7
Analysis:
1. if abs(num) < 7, return to_string(num). For example, 0 -> "0", -1 -> "-1", 1 -> "1", etc.
2. otherwise, we just need to consider (num/7) and (num%7). The second part can be converted to a string directly (need to pay attention to the negative values. For example, -8. num%7 == -1, but we just need "1" actually. So need to use the abse(num%7)). The first part can be calculated recursively.
See the code below:
class Solution {
public:
string convertToBase7(int num) {
// base
if(abs(num) < 7) return to_string(num);
// converging
return convertToBase7(num/7) + to_string(abs(num%7));
}
};
Comments
Post a Comment