주하니 서하아빠

504. Base7 본문

알고리즘/LeetCode

504. Base7

JUHANPAPA 2024. 1. 23. 14:20

 

Given an integer num, return a string of its base 7 representation.


Example 1:

Input: num = 100
Output: "202"

 

Example 2:

Input: num = -7
Output: "-10"

 

Constraints:

  • -107 <= num <= 107

 

풀이방법

풀이는 StringBuilder를 이용해서 간단하게 해결함.

num이 0보다 클 때까지 while문 수행하면서 7로 나눔.

0보다 작을때만 (isNagative == true) StringBuilder에 -를 붙여줌. 

마지막에 reverse로 반대로 출력함

class Solution {
    public String convertToBase7(int num) {
        if (num ==0) return "0";
        StringBuilder sb = new StringBuilder();
        boolean isNegative = num < 0;
        if (isNegative) num = -1 * num;
        while (num > 0) {
            int temp = num % 7;
            sb.append(temp);            
            num /= 7;
        }
        if (isNegative) sb.append("-");
        return sb.reverse().toString();
    }
}

 

'알고리즘 > LeetCode' 카테고리의 다른 글

1832. Check if the Sentence Is Pangram  (0) 2023.12.10
867. Transpose Matrix  (0) 2023.07.07
724. Find Pivot Index  (3) 2023.06.17
20. Valid Parentheses  (0) 2022.05.24
121. Best Time to Buy and Sell Stock  (0) 2022.05.20