华为机试题:有10个整数,使前面格数顺序向后移m个位置,最后m个数变成最前面m个数。计算移动后的整数序列的前m个数和后m个数的和。

问题描述:有10个整数,使前面格数顺序向后移m个位置,最后m个数变成最前面m个数。计算移动后的整数序列的前m个数和后m个数的和。
运行时间限制: 无限制
内存限制: 无限制
输入: 先输入10个整数,以空格分隔;
再输入移动个数(即整数m)
输出: 移动后的整数序列
移动后的整数序列的前m个和后m个数的和。
样例输入:
1 2 3 4 5 6 7 8 9 10
3
样例输出:
8 9 10 1 2 3 4 5 6 7
27 18

#include <iostream>
#include "string" //这里要和#include "string.h"区别开
using namespace std;

//将字符型数字转换成int型
void convert_str_int(string str_array[],int * int_array)
{
    for (int i = 0; i < 10; i++)
    {
        string str = str_array[i];
        int res = 0;
        for (int i = 0; i < str.length(); i++)
        {
            res = res + (str[i]-'0')*(pow(10,(str.length()-i-1)));//^异或符号,sqrt()开根号
        }
        *(int_array+i)= res;
    }
}
//移动m个数,并计算
void move_and_compute(int *array,int move_step,int *res_fore =0,int *res_back=0)
{
    int place = 10-move_step;
    int temp[10];
    int res_temp1=0;
    int res_temp2=0;
    //将后m个数前移,并计算其和
    for (int i = 0; i < move_step; i++)
    {
        temp[i] = *(array+place+i);
        res_temp2 = res_temp2+temp[i];
    }
    //将其余10-m个数后移
    for (int i = 0; i < place; i++)
    {
        temp[move_step+i] = *(array+i);
    }
    //计算整体排序后,后m个数之和
    for (int i = 0; i < move_step; i++)
    {
        res_temp1 = res_temp1 + temp[10-move_step+i];
    }
    //结果
    *res_fore = res_temp2;
    *res_back = res_temp1;
    for (int i = 0; i < 10; i++)
    {
        *(array+i) = temp[i];
    }
}
void remove_blank(string str,string *res)
{

    int index = 0;
    for (int i = 0; i < str.length(); i++)
    {
        int step_num = 0;
        string temp = "";
        for (int j = 0;' '!=str[i+j]&&i+step_num<str.length(); j++)
        {
            temp = temp+str[i+j];
            step_num++;
        }
        i = i+step_num;
        if (""!= temp)
        {
            *(res+index) = temp;
            index++;
        }
    }
}
int main()
{
    //接收带有空格的字符串
    string str(100,'0');
    cout<<"请输入10个数,用空格隔开:"<<endl;
    getline(cin,str);

    //接收移动的步长
    cout<<endl<<"请输入移动步长:";
    int move_step = 0;
    cin>>move_step;

    string num_array[10];//储存去空格之后的字符串
    int res_fore = 0;//存储前m个数之和的结果
    int res_back = 0;//存储后m个数之和的结果
    int res[10];//储存将字符转换成数字的结果

    //移除空格,将结果存放在num_array中
    remove_blank(str,num_array);
    //数字转换
    convert_str_int(num_array,res);
    //计算
    move_and_compute(res,move_step,&res_fore,&res_back);
    //输出结果
    cout<<"移动后的结果:"<<endl;
    for (int i = 0; i < 10; i++)
    {
        cout<<res[i]<<" ";
    }
    cout<<endl<<"前"<<move_step<<"个数的和为:"<<res_fore<<" "<<"后"<<10-move_step<<"个数的和为:"<<res_back<<endl;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值