力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。https://leetcode.cn/problems/base-7/description/
给定一个整数 num
,将其转化为 7 进制,并以字符串形式输出。
示例 1:
输入: num = 100 输出: "202"
示例 2:
输入: num = -7 输出: "-10"
提示:
-107 <= num <= 107
直接用Java的内置函数
class Solution {public String convertToBase7(int num) {return Integer.toString(num,7);}}
取余数倒置
class Solution {public String convertToBase7(int num) {if(num==0) {return "0";}boolean flag = false;if(num<0) {flag = true;num = num*(-1);}StringBuilder sb = new StringBuilder();while(num!=0) {sb.insert(0, String.valueOf(num%7));num = num/7;}if(flag) {sb.insert(0,'-');}return sb.toString();}}
C++ 的实现方式
class Solution {
public:string convertToBase7(int num) {if(num==0) {return "0";}int flag = 1;if(num<0) {flag = -1;num = -num;}string str = "";while(num>0) {str.insert(0,to_string(num%7));num /= 7;}if(flag==-1) {str.insert(0,"-");}return str;}
};