标签:
问题描述:数字加千分位:要求用户输入一个整数,编写一个方法,方法将将整数转换为一个从低位开始每三位一个逗号的“千分位”字符串表示形式。
//正向解法
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