CF周赛 B. Maximum Rounding 模拟

‍ B. Maximum Rounding

Given a natural number x x x. You can perform the following operation:

  • choose a positive integer k k k and round x x x to the k k k-th digit

Note that the positions are numbered from right to left, starting from zero. If the number has k k k digits, it is considered that the digit at the k k k-th position is equal to 0 0 0.

The rounding is done as follows:

  • if the digit at the ( k − 1 ) (k-1) (k1)-th position is greater than or equal to 5 5 5, then the digit at the k k k-th position is increased by 1 1 1, otherwise the digit at the k k k-th position remains unchanged (mathematical rounding is used).

  • if before the operations the digit at the k k k-th position was 9 9 9, and it should be increased by 1 1 1, then we search for the least position k ′ k' k (KaTeX parse error: Expected 'EOF', got '&' at position 3: k'&̲gt;k), where the digit at the k ′ k' k-th position is less than 9 9 9 and add 1 1 1 to the digit at the k ′ k' k-th position. Then we assign k = k ′ k=k' k=k.

  • after that, all digits which positions are less than k k k are replaced with zeros.

Your task is to make x x x as large as possible, if you can perform the operation as many times as you want.

For example, if x x x is equal to 3451 3451 3451, then if you choose consecutively:

  • k = 1 k=1 k=1, then after the operation x x x will become 3450 3450 3450
  • k = 2 k=2 k=2, then after the operation x x x will become 3500 3500 3500
  • k = 3 k=3 k=3, then after the operation x x x will become 4000 4000 4000
  • k = 4 k=4 k=4, then after the operation x x x will become 0 0 0

To maximize the answer, you need to choose k = 2 k=2 k=2 first, and then k = 3 k=3 k=3, then the number will become 4000 4000 4000.


AC code

import java.util.*;

public class Main
{
	public static void main(String[] args)
	{
		Scanner sc = new Scanner(System.in);
		int T = sc.nextInt();
		while (T-- > 0)
		{
			String x = sc.next();
			x = "0" + x;
			int len = x.length();
			char[] s = x.toCharArray();//转为 char 数组方便操作
			int p = len;
			for (int i = len - 1; i >= 0; i--)// i 从低位开始枚举,逢 >= 5 往高位进1
			{
				if (s[i] >= '5')
				{
					s[i - 1]++;
					p = i;// 记录已经进位的最高位,表示此位以后都是 0
				}
			}
//			如果有前导零,直接跳过										
			for (int i = (s[0] == '0') ? 1 : 0; i < s.length; i++)
			{
				System.out.print(i >= p ? '0' : s[i]);//找到最近的一个进位的位置,后边的全部置零
			}
			System.out.println();
		}
	}

}

你可能感兴趣的:(算法题解,java,开发语言)