Those numbers looks like abcd where a,b,c,d - all different and ab - cd = a+ b+c+d .
So to write it I choosed the way to change the numbers in strings. So now it really easy to check if conditions are met.
To transform int to string on C++ I used itoa function and to transform string to int on C++ I used atoi function.
To transform char to int on C++ I used code like this:
char s;
cin>>s;
int i = s - '0';So here is the code:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
// itoa : int to string;
// atoi : string to int;
int _tmain(int argc, _TCHAR* argv[])
{
string abs;
string cds;
int sum = 0;
int n;
for(int n = 1000; n < 10000; n++)
{
char buffer[5];
string str = itoa(n, buffer, 10);
int k = 1;
for(int i = 1; i< 4; i++)
if (str[i-1] != str[i])
k++;
if (k == 4)
{
abs = str[0];
abs += str[1];
cds = str[2];
cds += str[3];
sum += (str[0]-'0') + (str[1]-'0') + (str[2]-'0') + (str[3]-'0');
int iab = atoi(abs.c_str());
int icd = atoi(cds.c_str());
if (iab - icd == sum)
cout<<n<<endl;
sum = 0;
};
}
return 0;
}
No comments:
Post a Comment