当前位置:编程学习 > JAVA >>

Rounders

Introduction:
For a given number, if greater than ten, round it to the nearest ten, then (if that result is greater than 100) take the result and round it to the nearest hundred, then (if that result is greater than 1000) take that number and round it to the nearest thousand, and so on ...
Input:
Input to this problem will begin with a line containing a single integer n indicating the number of integers to round. The next n lines each contain a single integer x (0 ≤ x ≤ 99999999).
Output:
For each integer in the input, display the rounded integer on its own line.
Note: Round up on fives.
Sample Input:
9
15
14
4
5
99
12345678
44444445
1445
446
Sample Output:
20
10
4
5
100
10000000
50000000
2000
500
 
 
题意概述:给定一个整数,从右向左对每一位进行四舍五入,直至最左边的那一位。例如:12345,第一次运算后的结果:12340;第二次运算后的结果:12400;第三次运算后的结果:13000;第四次后的结果:10000.
 
解题思路:刚开始理解错题目了,以为只要看个位数,如果个位数大于4,就进位。我的想法是用字符串,之所以用字符串,是觉得字符串可以很方便的对每一位进行操作,而且易于进位。
 
源代码:
 
#include<iostream>
#include<string>
using namespace std;
int main()
{
    int T,L,C;
    string S;
    cin>>T;
    while(T--)
    {
         cin>>S;
         L=S.size();
         if(L>1)      //长度小于1的字符串不进行处理 
         {
              for(int i=L-1;i>0;--i)
              {
                      if(S[i]>='5')
                      { 
                          S[i]='0';
                          S[i-1]++;
                      }
                      else 
                      {
                           S[i]='0';
                      }
              }
              if(S[0]>'9') {S[0]='0';cout<<'1'<<S<<endl;}//最左端的那位会产生进位 
              else cout<<S<<endl;
         }
         else cout<<S<<endl;
    } 
    return 0;
}
补充:软件开发 , Java ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,