[LeetCode] 504. Base 7

题:https://leetcode.com/problems/base-7/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].

题目大意

将num 转为 7 进制值数。

思路

方法一 使用 stack进行翻转

求得 最低位 然后翻转。

class Solution {
    public String convertToBase7(int num) {
        boolean isNegative = false;
        Stack<Integer>   stack = new Stack<>();
        if(num<0){
            isNegative = true;
            num = -num;
        }
        do{
            stack.push(num%7);
            num = num/7;
        }while(num>0);
        StringBuilder strbuilder = new  StringBuilder();
        if(isNegative)
            strbuilder.append('-');
        while(!stack.isEmpty())
            strbuilder.append(stack.pop());
        return strbuilder.toString();
    }
}

方法二 使用 stringBuilder 自带翻转

class Solution {
    public String convertToBase7(int num) {
        boolean isNegative = false;
        StringBuilder strbuilder = new  StringBuilder();
 
        if(num<0){
            isNegative = true;
            num = -num;
        }
        do{
            strbuilder.append(num%7);
            num = num/7;
        }while(num>0);
        if(isNegative)
            strbuilder.append('-');
        return strbuilder.reverse().toString();
    }
}

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/83343947