Base7 [source code]

public class Base7 {
    public String convertToBase7(int num) {
        if (num == 0) return "" + 0;
        String res = "";
        boolean negative = false;
        if (num < 0) {
            negative = true;
            num = -num;
        }
        while (num > 0) {
            res = (num % 7) + res;
            num /= 7;
        }
        return (negative ? "-" : "") + res;
    }
}

这个算法总体还是很简单的, 不过我还是墨迹了快要十分钟才做出来, 只能说不熟练. 这种题目面试要是碰到必须无条件妙解.

另外这一题对于 emptycase 又忘记了处理了, 而很碰巧的是, 这一题的 emptycase 如果不处理, 就一定会报错.

速度是16ms, 81%, 还可以接受;


另外注意这一题是直接可以用 API 做的 :

public class Solution {  
    public String convertToBase7(int num) {  
        return Integer.toString(num,7);  
    }  
}

这个是 submission 最优解(15ms, 95%):

public class Solution {  
    public String convertToBase7(int num) {  
        if (num < 0) return "-" + convertToBase7(-num);  
        if (num < 7) return num + "";  
        return convertToBase7(num/7) + num % 7;  
    }  
}

其实就是用 recursion 来完成循环. 不知道为什么反而比我的要快;


discussion 上面基本也就是这两个解法(我的和这个 recursion 的), 没有其他更好的解法;


Problem Description

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].

Difficulty:Easy
Category:Algorithms
Acceptance:44.81%
Contributor: satyapriya

results matching ""

    No results matching ""