码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-02-11 00:22:11      阅读:225      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!