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

POJ 1312 Numerically Speaking

时间:2015-09-01 21:28:07      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

题意:a = 1, b = 2, ..., z = 26, aa = 27, ...

给字符串或者数字,输出对应的答案。

 

解法:类似26进制……但又不完全是……拿java大数模拟了一下……

 

代码:

import java.util.*;
import java.math.*;

public class Main 
{
	public static void main(String args[])
	{
		Scanner cin = new Scanner(System.in);
		while(true)
		{
			String input = cin.next();
			if(input.equals("*"))
				break;
			String ans1 = "", ans2 = "";
			if(input.charAt(0) >= ‘0‘ && input.charAt(0) <= ‘9‘)
			{
				ans2 = input;
				BigInteger x = new BigInteger(input);
				while(!x.equals(BigInteger.ZERO))
				{
					if(x.equals(BigInteger.valueOf(26)))
					{
						ans1 += ‘z‘;
						break;
					}
					ans1 += (char)(‘a‘ + (Integer.parseInt(x.mod(BigInteger.valueOf(26)).toString()) + 25) % 26);
					if(x.mod(BigInteger.valueOf(26)).equals(BigInteger.ZERO))
					{
						x = x.divide(BigInteger.valueOf(26));
						x = x.add(BigInteger.valueOf(-1));
					}
					else
						x = x.divide(BigInteger.valueOf(26));
				}
			}
			else
			{
				ans1 = input;
				BigInteger x = BigInteger.ZERO;
				for(int i = 0; i < input.length(); i++)
				{
					x = x.multiply(BigInteger.valueOf(26));
					x = x.add(BigInteger.valueOf((int)input.charAt(i) - ‘a‘ + 1));
				}
				ans2 = x.toString();
			}
			if(input.charAt(0) >= ‘0‘ && input.charAt(0) <= ‘9‘)
				for(int i = ans1.length() - 1; i >= 0; i--)
					System.out.print(ans1.charAt(i));
			else
				System.out.print(ans1);
			for(int i = 22 - ans1.length(); i > 0; i--)
				System.out.print(" ");
			int len = ans2.length() % 3;
			int res = ans2.length();
			for(int i = 0; i < len; i++)
				System.out.print(ans2.charAt(i));
			for(int i = len; i < res; i += 3)
			{
				if(i != 0)
					System.out.print(‘,‘);
				System.out.print(ans2.charAt(i));
				System.out.print(ans2.charAt(i + 1));
				System.out.print(ans2.charAt(i + 2));
			}
			System.out.println("");
		}
	}
}

  

POJ 1312 Numerically Speaking

标签:

原文地址:http://www.cnblogs.com/Apro/p/4776738.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!