中石油 ——5615:——Simple Calculator

本文介绍了一道关于计算器操作的问题,目标是最少步数将显示的整数从x变为y。文章提供了完整的C++代码实现,包括两种操作:加1和取反,并详细解释了不同情况下的最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Snuke has a calculator. It has a display and two buttons.

Initially, the display shows an integer x. Snuke wants to change this value into another integer y, by pressing the following two buttons some number of times in arbitrary order:

Button A: When pressed, the value on the display is incremented by 1.
Button B: When pressed, the sign of the value on the display is reversed.
Find the minimum number of times Snuke needs to press the buttons to achieve his objective. It can be shown that the objective is always achievable regardless of the values of the integers x and y.

Constraints
x and y are integers.
|x|,|y|≤109
x and y are different.

输入

The input is given from Standard Input in the following format:
x y

输出

Print the minimum number of times Snuke needs to press the buttons to achieve his objective.

水题,思路清晰一般不会错。

题意;给你x,y两个数,有两种操作:操作(1)x的数值+1,操作(2)x=-x;问你最少走多少步。

思路比较简单,就不写了

 
#include<stdio.h>
#include<math.h>
#include<string.h>
using namespace std;
#define ll long long
ll min(ll a,ll b ) {return a<b?a:b;}
ll max(ll a,ll b)  {return a>b?a:b;}
ll  minn(ll a,ll b,ll c){return min(min(a,b),min(b,c));}
ll  maxn(ll a,ll b,ll c){return max(max(a,b),max(b,c));}
int main()
{
    int x,y;
    scanf("%d%d",&x,&y);
    if(x==-y) printf("1\n");
    else if(x==0) {
        if(y>0) printf("%d\n",y);
        else printf("%d\n",-y+1);
    }
    else if(y==0)
    {
        if(x<0) printf("%d\n",-x);
        else printf("%d\n",x+1);
    }
    else if(0<x&&x<y) printf("%d\n",y-x);
    else if(0<y&&y<x) printf("%d\n",x-y+2);
    else if(x>0&&y<0)
    {
        if(x>-y) printf("%d\n",x+y+1);
        else if(x<-y) printf("%d\n",-y-x+1);
    }
    else if(x<0&&y>0)
    {
        if(-x<y) printf("%d\n",y+x+1);
        else printf("%d\n",-x-y+1);
    }
    else if(x<y&&y<0) printf("%d\n",y-x);
    else if(y<x&&x<0) printf("%d\n",x-y+2);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值