首页 > 专题系列 > Java解POJ > POJ 3077 Rounders [解题报告] Java
2013
11-12

POJ 3077 Rounders [解题报告] Java

Rounders

问题描述 :

For a given number, if greater than ten, round it to the nearest ten, then (if that result is greater than 100) take the result and round it to the nearest hundred, then (if that result is greater than 1000) take that number and round it to the nearest thousand, and so on …

输入:

Input to this problem will begin with a line containing a single integer n indicating the number of integers to round. The next n lines each contain a single integer x (0 <= x <= 99999999).

输出:

For each integer in the input, display the rounded integer on its own line.

Note: Round up on fives.

样例输入:

9
15
14
4
5
99
12345678
44444445
1445
446

样例输出:

20
10
4
5
100
10000000
50000000
2000
500

解题代码:

方法一:
import java.math.BigInteger;
import java.util.*;

public class Main
{

    public static void main(String args[])
    {
       int n, s, i;
       Scanner cin = new Scanner( System.in );
       n = cin.nextInt();
       while( n-- != 0 ) {
    	   s = cin.nextInt();
    	   for( i=10; i<=100000000; i*=10 )
    		   if( s >= i ) {
    			   s = (s+i/2)/i*i;
    		   }
    	   System.out.println( s );
       }
       return;
    }
}

方法二:
//* @author 洪晓鹏<[email protected]>
import java.util.Scanner;

public class Main{

/**
 * @param args
 */
public static void main(String[] args) {
	// TODO Auto-generated method stub
	Scanner in = new Scanner(System.in);
	int n = Integer.parseInt(in.nextLine());
	for (int i = 0; i < n; i++) {
		String s = in.nextLine();
		int len = s.length();
		int carry = 0;
		if (len == 1) {
			System.out.println(s);
			continue;
		}
		for (int j = len - 1; j > 0; j--) {
			if ((s.charAt(j) - '0' + carry) >= 5)
				carry = 1;
			else
				carry = 0;
		}
		int f = s.charAt(0) - '0' + carry;
		String result = "" + f;
		for (int j = 0; j < len - 1; j++) {
			result += "0";
		}
		System.out.println(result);
	}
  }

}

  1. 第二个方法挺不错。NewHead代表新的头节点,通过递归找到最后一个节点之后,就把这个节点赋给NewHead,然后一直返回返回,中途这个值是没有变化的,一边返回一边把相应的指针方向颠倒,最后结束时返回新的头节点到主函数。

  2. 代码是给出了,但是解析的也太不清晰了吧!如 13 abejkcfghid jkebfghicda
    第一步拆分为 三部分 (bejk, cfghi, d) * C(13,3),为什么要这样拆分,原则是什么?