校内选拔第一题解题方法

链接:登录—专业IT笔试面试备考平台_牛客网
来源:牛客网
 

Bessie is working with large numbers N (1 <= N <= 2,000,000,000) like 153920529 and realizes that the numbers would be a lot easier to read with commas inserted every three digits (as is normally done in the USA; some countries prefer to use periods every three digits). Thus, she would like to add commas: 153,920,529 . Please write a program that does this.

输入描述:

* Line 1: A single integer: N

输出描述:

* Line 1: The integer N with commas inserted before each set of three digits except the first digits (as traditionally done in many cultures)

示例1

输入

复制153920529

153920529

输出

复制153,920,529

153,920,529

我组代码如下:

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    long long N; int a, b, c, d;
    cin >> N;//   N = ?,???,???,???
    d = N % (int)1e3;        //只取后三位
    c = (N / (int)1e3) % 1000;//先取千及以上位的数,再只取后三位数
    b = (N /(int)1e6) % 1000;//先取百万及以上位的数,再只取后三位的数
    a = (N / 1e9);//只取最前一位
    if (N >= 1 && N <= 999)   //没有逗号
    {
        cout << d << endl;
    }
    else if (N < 1e6)   //有一个逗号
    {
        cout << c << ',' << setw(3) << setfill('0') << d << endl;
    }
    else if (N < 1e9)  //有两个逗号
    {
        cout << b
            << ',' << setw(3) << setfill('0') << c
            << ',' << setw(3) << setfill('0') << d << endl;
    }
    else if (N <= 2e9) //有三个逗号
    {
        cout << a
            << ',' << setw(3) << setfill('0') << b
            << ',' << setw(3) << setfill('0') << c
            << ',' << setw(3) << setfill('0') << d << endl;
    }
    return 0;
}







最后的结果是成功了,通过了所有测试用例。

这是我稍作修改后的代码,我组提交的代码中没有用到1e9等的写法而是直接写了很多零。

现在我使用了科学计数法,很显然编译器报错,说表达式必须具有整数或未区分范围的枚举类型。于是我将1e3,1e6都给强制转化为了int型,然而,我没有给最后的a的计算表达式中的1e9强制转化,但程序却意外地能正常运行,本人表示很不解。

请求诸位略做解答!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值