#leetcode# Base 7

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ChiBaoNeLiuLiuNi/article/details/55047529

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

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

分析: 将数字转换为7进制,以100为例:

100 % 7  = 2

100 / 7 = 14

14 % 7 = 0

14 / 7 = 2

2 % 7 = 2

2 / 7 = 0


100 —> 202


不难看出就是一个不断对7取模,然后除以7,然后用除以7之后的数字重复这一循环,直到数字变成0


public class Solution {
    public String convertTo7(int num) {
        if(num == 0)
            return "0";
        boolean neg = num < 0 ? true : false;
        StringBuilder sb = new StringBuilder();
        num = Math.abs(num);
        while(num > 0){
            int cur = num % 7;
            sb.append(String.valueOf(cur));
            num /= 7;
        }
        if(neg)
            sb.append('-');
        
        return sb.reverse().toString();
    }
}


自己写代码的时候忘记了 num ==0 这个特殊情况。。。

对可能的corner case还是不够敏锐


猜你喜欢

转载自blog.csdn.net/ChiBaoNeLiuLiuNi/article/details/55047529