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();
		}
	}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值