P1307 [NOIP2011 普及组] 数字反转 题解

  • C语言 实现
// -*- coding: utf-8 -*-
//  @ Date   : 2020/5/20 13:14
//  @ Author : RichardLau_Cx
//  @ file   : Richard.c
//  @ IDE    : Dex-C++
//  @ Source : luogu

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
	// C语言方法
	char num[10];
	int lens;
	int indexF=0;  // 字符数组开头索引 
	int indexB=0;  // 字符数组结尾索引 
	int flag = 1;  // 正负标志 
	int nums;
	
	gets(num);
	lens = strlen(num);
	
	for (int i=0; i < lens/2; i++)
	{  // 注意第一个值的索引为0 
		char temp;
		temp = num[i];
		num[i] = num[lens-i-1];
		num[lens-i-1] = temp;
	}
	
	if (num[lens-1] == '-')
	{
		indexB = lens-2;
		flag *= -1; 
	 } 
	 
	nums = atoi(num);
	printf("%d", nums * flag);
	
	return 0;
 } 
  • C++ 实现
// -*- coding: utf-8 -*-
//  @ Date   : 2020/5/20 13:14
//  @ Author : RichardLau_Cx
//  @ file   : Richard.cpp
//  @ IDE    : Dex-C++
//  @ Source : luogu

#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
	// 字符串方法
	string nums;
	int len;
	int index = 0;
	int flag = 1;
	int num;
	int s = 1;  // 若为正数是1,负数则为0 
	
	cin >> nums;
	len = nums.length();
	
	if (nums[0] == '-')
	{
		index = 1;
		flag = -1;
		s = 0;
	}
		
	for (int i=index; i<len/2; i++)
	{  // 必须取一半,不然将会换回来 
		// 同时不把符号算进去交换的话,最后得到的交换结果即包括了正负 
		char temp = nums[i];
		nums[i] = nums[len-i-s];
		nums[len-i-s] = temp;
	}
	
	istringstream is(nums);  // 构造输入字符串流
	is >> num; 
	
	cout << num;
	
	return 0;
 } 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值