Results 1 to 6 of 6
Hi long time no see, I just returned for my holiday and I already have a Math Problem stuck in my head that I cant solve.
So I thought Id ...
- 01-05-2008 #1
Math Problem C++
Hi long time no see, I just returned for my holiday and I already have a Math Problem stuck in my head that I cant solve.
So I thought Id bruteforce it with C++
But I have to do one thing and I have no idea how..
I have 2 variables A and B.
B is A Swapped.
So, if A equals 1 B also equals 1. But if A equals 20 B equals 2.
So Basicly you'll get this:
A = 1 B = 1
A = 12 B = 21
A = 23 B = 32
A = 34 B = 43
A = 45 B = 54
I hope I made a Sketch of the Problem now.
Does anyone know how to solve this??
Thanks,
Cheers,
Robin
- 01-06-2008 #2
I could tell you, but then I'd have to kill you. (Just kidding.)
Why not have a go at it yourself and post what you have?--
Bill
Old age and treachery will overcome youth and skill.
- 01-06-2008 #3
This might help
#include <iostream>
int main(int argc, char**argv)
{
char ch[2];
ch[1] = '\0';
int x = 0;
int y = 0;
int count = 1;
const int MULTI = 1;
std::cout<<"enter a number->";
while ((ch[0] = std::cin.get()) != '\n')
{
if (isdigit(ch[0]))
{
y = strtol(ch, NULL, 10);
x = (MULTI * count) * y + x;
count = count * 10;
}
}
std::cout<<"x->"<<x<<"\n";
return 0;
}
This is not exactly what your looking for...but its a start
- 01-06-2008 #4
- 01-06-2008 #5
Use Modulus (%
operator to extract last digit.
e.g.
A =123
B = ( A % 10 )
B will get 3. Its remainder of A / 10.
You can extract every digit and do whatever you want.
Armstrong, Palindrome or Reverse numbers.It is amazing what you can accomplish if you do not care who gets the credit.
New Users: Read This First
- 01-06-2008 #6Linux Enthusiast
- Join Date
- Aug 2006
- Posts
- 631
Two possibilies, the second function should be faster:
Function with modulo operator:
String version:Code:#include <stdio.h> int reverse(int value); int main () { int val; scanf("%d", &val); printf("Reverse value: %d\n", reverse(val)); return(0); } int reverse(int value) { int val, rev = 0; val=value; while(val) { rev*=10; rev+=val%10; val/=10; } return rev; }
Code:#include <stdio.h> #include <string.h> int reverse(int value); int main () { int val; scanf("%d", &val); printf("Reverse value: %d\n", reverse(val)); return(0); } int reverse(int value) { char str[20], rts[20]; int i = 0, len; sprintf(str, "%d", value); len = strlen(str) - 1; while(str[i]) { rts[i]=str[len]; i++; len--; } rts[i] = '\0'; return atoi(rts); }
Regards


Reply With Quote
