C++数组连接求能被7整除的数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/oqqENvY12/article/details/77985288

2018美团点评编程题2

wangzhi

lalal

思路:若一个整数的个位数字截去,再从余下的数中,减去个位数的2倍,如果差是7的倍数,则原数能被7整除。如果差太大或心算不易看出是否7的倍数,就需要继续上述「截尾、倍大、相减、验差」的过程,直到能清楚判断为止。例如,判断133是否7的倍数的过程如下:13-3×2=7,所以133是7的倍数;又例如判断6139是否7的倍数的过程如下:613-9×2=595 , 59-5×2=49,所以6139是7的倍数,余类推。

#include <iostream>
#include <vector>
#include <cstdlib>  
#include <string>
#include<stdio.h> 
using namespace std;

bool devide7(int x) {
    int m = x % 10;
    int n = (x - m) / 10;
    int p = n - 2 * m;
    if (0 == (p % 7))
        return true;
    else
        return false;
}

//int 转string  
string intToString(int num) {
    char p[255];
    sprintf_s(p, "%d", num);
    string s(p);
    return s;
}

//string转int  
int stringToint(const string&s) {
    return atoi(s.c_str());
}

int main() {
    int x = 0;
    int y = 0;
    static int num = 0;
    cin >> x;
    vector<int> inputs;

    for (int i = 0; i < x; i++) {
        cin >> y;
        inputs.push_back(y);
    }

    for (int i = 0; i < x; i++) {
        for (int j = i+1; j < x; j++) {
            string temp1 = intToString(inputs[i]) + intToString(inputs[j]);
            int temp3 = stringToint(temp1);
            if (devide7(temp3))
                num++;

        }
    }

    for (int i = x-1; i >=0; i--) {
        for (int j = i - 1; j >=0; j--) {
            string temp1 = intToString(inputs[i]) + intToString(inputs[j]);
            int temp3 = stringToint(temp1);
            if (devide7(temp3))
                num++;
        }
    }

    cout << num << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/oqqENvY12/article/details/77985288