HDU 1266

今天写了基础题,是关于整型数翻转的,虽然不难,但是看到杭电讨论版块一些人说要注意前导0的错误说法,所以打算写一篇博客说明一下。(如果我说错了,请大家批评指正!)

首先这道题不存在有前导0的问题,因为题目给出了各种情况下的翻转方法,其中并没有说明如何处理前导0,所以如果题目和测试数据是严谨的话,就不该出现这种没有说明处理方法的特殊情况。实际上我的代码没有处理前导0,而且出现前导0的话,我的程序也不能得到像讨论版块中那样的前导0的处理结果,但也AC了,所以这道题无需处理前导0。

然后谈谈我的思路。我用了字符数组来保存输入的数据,所以整数翻转就是一个局部(例如:1200)或全体(例如:12)倒序输出的问题。要注意的是程序在找后导0时要从最后一位向前找,如果从前往后找就要考虑如何处理中间的0(例如:908900),不过那样貌似挺麻烦的!其他的应该没有特别需要指出注意的,大家都能想到。

代码(G++):

#include <cstdlib>
#include <iostream>
#define MAX 20

using namespace std;

int main(int argc, char *argv[])
{
    int n,i,digit,start,end;          //start标记了第一个'0'或'\0'的位置,end标记了第一个数字的位置 
    char number[MAX];
    cin>>n;
    while(n--)
    {
       cin>>number;
       start=end=0;
       if('-'==number[0])
       {
          cout<<'-';
          end++;
       } 
       while(number[start]!='\0') start++;         //找到字符串的末尾                                                   
       while(start-1>=0&&'0'==number[start-1]) start--;     //找到后导0的第一位 
       if(start!=end)
       {
          for(i=start-1;i>=end;i--)  cout<<number[i];      //倒序输出数字                                                    
       }
       while(number[start]!='\0')        //输出可能存在的'0' 
       {
          cout<<number[start];
          start++;                      
       }
       cout<<endl;     
    }
    system("PAUSE");
    return EXIT_SUCCESS;
}

附上原题:

Reverse Number

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)


Problem Description
Welcome to 2006'4 computer college programming contest!

Specially, I give my best regards to all freshmen! You are the future of HDU ACM! And now, I must tell you that ACM problems are always not so easy, but, except this one... Ha-Ha!

Give you an integer; your task is to output its reverse number. Here, reverse number is defined as follows:
1. The reverse number of a positive integer ending without 0 is general reverse, for example, reverse (12) = 21;
2. The reverse number of a negative integer is negative, for example, reverse (-12) = -21;
3. The reverse number of an integer ending with 0 is described as example, reverse (1200) = 2100.
 

Input
Input file contains multiple test cases. There is a positive integer n (n<100) in the first line, which means the number of test cases, and then n 32-bit integers follow.
 

Output
For each test case, you should output its reverse number, one case per line.
 

Sample Input
  
  
3 12 -12 1200
 

Sample Output
  
  
21 -21 2100

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值