【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
原创粉丝点击