Wrong Subtraction (减法错误)

文章描述了一个编程问题,其中Tanya有一个减法算法:如果数字的最后一位非零,则减1;如果最后一位是零,则去掉这一位。给定一个数字n和次数k,需要计算执行这个算法k次后n的结果。示例展示了如何从512开始,经过4次操作得到50。
摘要由CSDN通过智能技术生成

题目描述

Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:

  • if the last digit of the number is non-zero, she decreases the number by one;
  • if the last digit of the number is zero, she divides the number by 10 (i.e. removes the last digit).

You are given an integer number nn . Tanya will subtract one from it kk times. Your task is to print the result after all kk subtractions.

It is guaranteed that the result will be positive integer number.

输入格式

The first line of the input contains two integer numbers nn and kk ( 2 \le n \le 10^92≤n≤109 , 1 \le k \le 501≤k≤50 ) — the number from which Tanya will subtract and the number of subtractions correspondingly.

输出格式

Print one integer number — the result of the decreasing nn by one kk times.

It is guaranteed that the result will be positive integer number.

sample inputsample output
512  450

题意翻译

题目描述

已知一个数 n ,你要对它进行 k 次操作。对于每一次操作,如果 n 的最后一位数字不为零,则将它减1,否则将它除以10(即删除最后一位数字)。

给出初始时的数 nn和操作次数 k,求操作 k次后的结果。

保证结果是正整数。

题目分析(说明 / 提示)

例: n = 512, k = 4.    (改四次)

512 → 511 → 510 → 51 → 50 .

第一次: 判断512的末尾是否为零,512末尾不为零,则减一,得511.

第二次: 判断511的末尾是否为零,511末尾不为零,则减一,得510.

第三次: 判断510的末尾是否为零,510末尾为零,则除10(即删除最后一位数字),得51.

第四次: 判断51的末尾是否为零,51末尾不为零,则减一,得50.

所以,最后n = 50,输出n.

参考代码

#include <bits/stdc++.h>
using namespace std;
int modification(int n, int k) //定义一个修改所输入的数的函数,需要导入n 与m .     
{
	for(int i = 0; i < k; i++) //要改变k 次 
	{
		if (n % 10 == 0) //如果n 的末尾为零,则可以判断出现在的n 为整十数.
		{
			n /= 10; //去除n 的末尾的零.
		}
		else if (n % 10 != 0) //如果n 的末尾不为零,则可以判断出现在的n 不为整十数.
		{
			n = n - 1; // 把n 减除1 . 
		}
	}
	return n; //返回最后计算出的n . 
}
int main()
{
	int n, k;
	cin >> n >> k;
	cout << modification(n, k); // 使用函数并输出 
	return 0;
}

/*
	拓展:
       modification
       n.修改的行为(过程);修改,更改;修饰
*/

        题目出自:洛谷题库

        网址:Wrong Subtraction - 洛谷https://www.luogu.com.cn/problem/CF977A

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值