首页 > 学院 > 开发设计 > 正文

504. Base 7

2019-11-06 08:34:34
字体:
来源:转载
供稿:网友

Given an integer, return its base 7 string rePResentation.

Example 1:

Input: 100Output: "202"

Example 2:

Input: -7Output: "-10"

Note: The input will be in range of [-1e7, 1e7].

public class demo1 {		public String convertToBase7(int num) {					String result="";				if(num==0) result="0";		int number=Math.abs(num);		while (number>0) {			int b=number%7;			number=number/7;			result=String.valueOf(b)+result;		}				if(num<0) {			result="-"+result;					}		return result;			}				public static void main(String[] args){    	int num=-7;    	demo1 r = new demo1();         	System.out.println(r.convertToBase7(num));	}}提交答案后,看到leetcode讨论区中的一个答案,只有五行,递归,简单到爆,特地copy过来膜拜膜拜。

public String convertToBase7(int num) {		 if (num < 0)		        return '-' + convertToBase7(-num);		    if (num < 7)		        return num + "";		    return convertToBase7(num / 7) + num % 7;		  	    	}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表