今天做了下英雄会在在线挑战,题目是
完成函数reverse,要求实现把给定的一个整数取其相反数的功能,举两个例子如下:
- x = 123, return 321
- x = -123, return -321
地址是http://hero.pongo.cn/Question/Details?ID=50&ExamID=48
我提交的代码是
// reverseIntergerTest.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include<cstdio> #include<iostream> using namespace std; int reverse(int x) { int remainder; //旋转后的数 int result = 0; bool negative = false; //要旋转的数是负数,则记录,并改为正数 if(x < 0) { x = -x; negative = true; } while(x != 0) { remainder = x%10; x = x/10; result = result * 10 + remainder; } if(negative == true) result = - result; return result; } int _tmain(int argc, _TCHAR* argv[]) { int number1 = 123; int number2 = -123; int result1 = reverse(number1); int result2 = reverse(number2); cout<<"Orignal number"<<number1<<" After reverse:"<<result1<<endl; cout<<"Orignal number"<<number2<<" After reverse:"<<result2<<endl; return 0; }
感觉很初级呢
时间: 2024-11-02 21:26:48