当前位置:网站首页>leetcode 504. Base 7 七进制数 (简单)
leetcode 504. Base 7 七进制数 (简单)
2022-08-02 14:36:00 【okokabcd】
一、题目大意
https://leetcode.cn/problems/base-7
给定一个整数 num,将其转化为 7 进制,并以字符串形式输出。
示例 1:
输入: num = 100
输出: “202”
示例 2:
输入: num = -7
输出: “-10”
提示:
- -107 <= num <= 107
二、解题思路
输入一个整数,输出一个字符串,表示其七进制。
进制转换类的题,通常是利用除法和取模来进行计算,同时也要注意一些细节,如负数和零。如果输出是数字类型而非字符串,则也需要考虑是否会超出整数上下界。
举例:100,求其7进制
100 / 7 = 14 ...... 2
14 / 7 = 2 ...... 0
七进制数为最后一位商+余数倒排
三、解题方法
3.1 Java实现
public class Solution {
public String convertToBase7(int num) {
if (num == 0) {
return "0";
}
boolean isNegative = num < 0;
num = isNegative ? -num : num;
StringBuilder ans = new StringBuilder();
while (num >= 7) {
int a = num / 7;
int b = num % 7;
ans.append(b);
num = a;
}
ans.append(num);
return (isNegative ? "-" : "") + ans.reverse();
}
}
四、总结小记
- 2022/8/2 余数和模的区别?
边栏推荐
猜你喜欢
随机推荐
PAT甲级 1143 最低公共祖先
Servlet运行原理_API详解_请求响应构造进阶之路(Servlet_2)
622. 设计循环队列 : 数组模拟循环队列
状态码以及访问百度过程
codeforces Linova and Kingdom
自定义属性
2022-07-18 第五小组 瞒春 学习笔记
容器中的Cgroup
VsCode更新后,怎么使用使用快捷键同时生成多个元素
Drag and Drop in H5
Redis + Caffeine实现多级缓存
浅析PM2实用入门指南
Wigner-Ville distribution for time-frequency analysis
PAT甲级 1078 哈希
codeforces k-Tree (dp still won't work)
电设3----脉冲信号测试仪
单例模式(singleton pattern)
【JS执行机制】
PAT甲级 1019 普通回文数
什么是hashCode?