LeetCode-Base 7

xiaoxiao2025-08-13  27

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

题意:给定一个数,输出其7进制表示;

解法:就像计算二进制表示一样,用7去整除这个数,保存其余数;

Java
class Solution { public String convertToBase7(int num) { if (num == 0) return "0"; int symbol = num >= 0 ? 1 : -1; StringBuilder sb = new StringBuilder(); num = Math.abs(num); while (num > 0) { sb.insert(0, num % 7); num /= 7; } if (symbol == -1) sb.insert(0, "-"); return sb.toString(); } }
转载请注明原文地址: https://www.6miu.com/read-5034802.html

最新回复(0)