【LeetCode】Base 7 解题报告
来源:互联网 发布:詹姆斯生涯数据统计 编辑:程序博客网 时间:2024/06/06 02:53
【LeetCode】Base 7 解题报告
标签(空格分隔): LeetCode
题目地址:https://leetcode.com/problems/base-7/#/description
题目描述:
Given an integer, return its base 7 string representation.
Example:
Input: 100Output: "202"Input: -7Output: "-10"
Ways
进制转换在java里特别简单。首先用Integer类的toString()。
public class Solution { public String convertToBase7(int num) { return Integer.toString(num,7); }}
之前用过的BigInteger类。
import java.math.BigInteger;public class Solution { public String convertToBase7(int num) { return new BigInteger("" + num, 10).toString(7); }}
用数学方法,判断正负之后,逐位求:
public class Solution { public String convertToBase7(int num) { if(num == 0){ return "0"; } StringBuilder ans = new StringBuilder(); boolean isNeg = num < 0; num = Math.abs(num); while(num != 0){ ans.append("" + (num % 7)); num /= 7; } if(isNeg){ ans.append("-"); } ans.reverse(); return ans.toString(); }}
用倍数相加的方法:
public class Solution { public String convertToBase7(int num) { if (num == 0) return "0"; int sign = (num > 0 ? 1 : -1); long res = 0; // 因为base7会比base10的数字要长, 防止越界,必须用long int digit = 1; // 位数,从个位开始 num *= sign; while (num > 0) { res += (num % 7) * digit; digit *= 10; num /= 7; } return String.valueOf(res * sign); }}
Date
2017 年 4 月 16 日
0 0
- 【LeetCode】Base 7 解题报告
- [Leetcode] 504. Base 7 解题报告
- LeetCode 483 Smallest Good Base 解题报告
- [Leetcode] 483. Smallest Good Base 解题报告
- LeetCode 7 Reverse Integer 解题报告
- LeetCode 解题报告索引
- [LeetCode]Permutations,解题报告
- Leetcode Triangle 解题报告
- [LeetCode]Anagrams,解题报告
- leetCode解题报告
- [LeetCode]Candy, 解题报告
- 【LeetCode】Candy 解题报告
- 【LeetCode】Triangle 解题报告
- 【LeetCode】Permutations 解题报告
- LeetCode 解题报告 LinkedListCycleII
- LeetCode 解题报告 Candy
- 【LeetCode】Anagrams 解题报告
- 【LeetCode】Combinations 解题报告
- 求某个数n的某一个因子的个数 (高斯取整函数思想)
- 操作mysql的相关错误
- 向量的点乘和叉乘在游戏中的应用
- spring项目的单元测试编写
- 文章标题
- 【LeetCode】Base 7 解题报告
- angular 之 ng-cloak,ng-cloak没效果
- Java的String类型比较
- Js_面向对象_02
- Unity3D学习(4)——摄像机&光源&面向对象&简单工厂
- 当互联网企业遇到了 SAFe, 是一拍即合? 还是存在著误解?!
- Linux内核之 中断以及中断处理程序
- 机器学习(Machine Learning)&深度学习(Deep Learning)资料(Chapter 2)
- Android ActionBar完全解析,使用官方推荐的最佳导航栏(上)