首页 > 其他 > 详细

两种方法解决数字加千分位问题(没考虑负数和小数)

时间:2015-02-11 00:20:48      阅读:353      评论:0      收藏:0      [点我收藏+]

问题描述:数字加千分位:要求用户输入一个整数,编写一个方法,方法将将整数转换为一个从低位开始每三位一个逗号的“千分位”字符串表示形式。

//正向解法

package ThirdTest;
import java.util.Scanner;
public class No2
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
thousand(num);
sc.close();
}
static void thousand(int num)
{
String str=Integer.toString(num);
String s="";
int count=0;
if(str.length()%3!=0)
{
count=3-str.length();
}
for(int i=0;i<str.length();i++)
{

count++;
s+=str.charAt(i);
if(count%3==0&&i!=str.length()-1)
{
s+=",";
count=0;
}
}
System.out.println(s);
}
}
//逆向解法
package ThirdTest;

import java.util.Scanner;

public class No22
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
String result=thousand(num);
System.out.println(result);
sc.close();

}
static String thousand(int num)
{
String str=Integer.toString(num);
String result="";
int count=0;
for(int i=str.length()-1;i>=0;i--)
{
count++;
result=str.charAt(i)+result;
if(count%3==0&&i!=0)
{
result=","+result;
}
}
return result;
}
}

两种方法解决数字加千分位问题(没考虑负数和小数)

原文:http://www.cnblogs.com/vtily/p/4285097.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!