#include<iostream>
using namespace std;
int change(int *a, int *b, int k, int l)
{
int changeAtoB, changeBtoA,countA=0,countB=0,copyA=*a,copyB=*b;
while (copyA != 0)
{
changeAtoB = copyA % 10;
copyA /= 10;
if (countA == k) copyA = 0;
else countA++;
}
while (copyB != 0)
{
changeBtoA = copyB % 10;
copyB /= 10;
if (countB == l) copyB = 0;
else countB++;
}
countA = 0, countB = 0;
int resultA = 0, resultB = 0;
while (*a !=0)
{
if (countA == k) resultA = resultA * 10 + changeBtoA;
else resultA = resultA * 10 + *a % 10;
*a /= 10;
countA++;
}
while (*b != 0)
{
if (countB == l) resultB = resultB * 10 + changeAtoB;
else resultB = resultB * 10 + *b % 10;
*b /= 10;
countB++;
}
*a = 0; *b = 0;
while (resultA != 0)
{
*a = *a * 10 + resultA % 10;
resultA /= 10;
}
while (resultB != 0)
{
*b = *b * 10 + resultB % 10;
resultB /= 10;
}
return 0;
}
void main()
{
int a, b;
int k, l;
cin >> a >> b >> k >> l;
change( &a, &b, k, l);
cout << a << " " <<b << endl;
system("pause");
}
int p10[] = {0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 1000000000};
int change(int *a, int *b, int k, int l)
{
int rk, rl;
if(k <= 0 || k > 9 || l <= 0 || l > 9) return 1;
rk = ((*a/p10[k])%10);
rl = ((*b/p10[l])%10);
*a = *a - (rk*p10[k]) + (rl*p10[k]);
*b = *b - (rl*p10[l]) + (rk*p10[l]);
return 0;
}
только это не перегруженная функция.
#include <iostream>
using namespace std;
unsigned power10(unsigned y) {
unsigned result = 1;
while(y--)
result = (result << 3) + (result << 1);
return result;
}
int sign(int a) {
if(a < 0)
return -1;
else
return 1;
}
void swap(int& a, int& b, unsigned k, unsigned l) {
const int multiply_a = power10(k);
const int multiply_b = power10(l);
const int digit_a = sign(a) * (a / multiply_a) % 10;
const int digit_b = sign(b) * (b / multiply_b) % 10;
const int add_a = multiply_a * digit_b - multiply_a * digit_a;
const int add_b = multiply_b * digit_a - multiply_b * digit_b;
a = a + sign(a)*add_a;
b = b + sign(b)*add_b;
}
int main() {
{
int a = 12345;
int b = 98765;
cout << a << ", " << b << " : ";
swap(a, b, 1, 4);
cout << a << ", " << b << endl;
}
{
int a = -12345;
int b = 98765;
cout << a << ", " << b << " : ";
swap(a, b, 1, 4);
cout << a << ", " << b << endl;
}
{
int a = -12345;
int b = -98765;
cout << a << ", " << b << " : ";
swap(a, b, 1, 4);
cout << a << ", " << b << endl;
}
return 0;
}