The program must accept an integer N with even number of digits as the input.
The program must reverse every two digits in N and print the modified N as the output.
Boundary Condition(s): 10 <= N < 10^16
Input Format: The first line contains N.
Output Format: The first line contains the modified N.
Example Input/Output 1:
Input: 214587
Output: 125478
Explanation: The first two digits are 2 and 1 which are reversed as 1 and 2. The second two digits are 4 and 5 which are reversed as 5 and 4. The third two digits are 8 and 7 which are reversed as 7 and 8.
Example Input/Output 2:
Input: 504786
Output: 57468
I have proceeded in a logic of printing the values inside a while loop by printing b/10 and b%10; where the output should be reversed and I am stuck in it, please help in my logic how to proceed further thank you.
scanf("%d",&a);
while(a>0) {
b=a%100;
printf("%d%d",b/10,b%10);
a=a/100;
}
As I noted in three comments (1, 2, 3), I think you need to use recursion, and some care. Here is code that works, and a test harness (which is bigger than the code being tested) demonstrating that it works:
#include <inttypes.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
static bool reverse_digit_pairs(uint64_t value)
{
uint64_t b = value % 100;
uint64_t v = value / 100;
if ((v > 0 && v < 10) || (v == 0 && b < 10))
return false;
int t = b / 10; // tens
int u = b % 10; // units
bool ok = true;
if (v >= 10)
ok = reverse_digit_pairs(v);
if (ok)
{
if (u == 0 && v == 0)
printf("%d", t);
else
printf("%d%d", u, t);
}
return ok;
}
static void test_reverse_digit_pairs(uint64_t v)
{
printf("V: %20" PRIu64 " = ", v);
if (!reverse_digit_pairs(v))
{
fprintf(stderr, "Odd number of digits in %" PRIu64 "\n", v);
printf("bogus input");
}
putchar('\n');
fflush(0); // Ensure standard output (and standard error) are flushed.
}
int main(void)
{
test_reverse_digit_pairs(UINT64_C(214587)); // 125478 per question
test_reverse_digit_pairs(UINT64_C(504786)); // 57468 per question
test_reverse_digit_pairs(UINT64_C(5047000086)); // Pairs of zeros
test_reverse_digit_pairs(UINT64_C(5047900086)); // Pair of zeros
test_reverse_digit_pairs(UINT64_C(1234567890123456)); // 16 digits
test_reverse_digit_pairs(UINT64_MAX); // 20 digits
test_reverse_digit_pairs(UINT64_C(123456789012345)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(0)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(1)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(9)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(10)); // 2 digits
test_reverse_digit_pairs(UINT64_C(99)); // 2 digits
test_reverse_digit_pairs(UINT64_C(100)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(999)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(1000)); // 4 digits
test_reverse_digit_pairs(UINT64_C(1098)); // 4 digits
test_reverse_digit_pairs(UINT64_C(1234)); // 4 digits
return 0;
}
The output I get from it is:
V: 214587 = 125478
V: 504786 = 57468
V: 5047000086 = 574000068
V: 5047900086 = 574090068
V: 1234567890123456 = 2143658709214365
V: 18446744073709551615 = 81447644707390556151
Odd number of digits in 123456789012345
V: 123456789012345 = bogus input
Odd number of digits in 0
V: 0 = bogus input
Odd number of digits in 1
V: 1 = bogus input
Odd number of digits in 9
V: 9 = bogus input
V: 10 = 1
V: 99 = 99
Odd number of digits in 100
V: 100 = bogus input
Odd number of digits in 999
V: 999 = bogus input
V: 1000 = 100
V: 1098 = 189
V: 1234 = 2143
The test cases for the numbers with 1 to 4 digits were necessary to flush out some issues. I'm not completely happy with the first condition in reverse_digit_pairs(), but I didn't get the output I think is required when I tried some simplifications.
Related
I've already written a program, but it's a bit incorrect.
I will be very grateful if you show me how to fix it.
So, here is the trouble:
You have to convert the number from hexadecimal to decimal form.
The main problem is that program must CALCULATE MANUALLY the number , instead of using a format specification ( as i did )
I apologize for possible inaccuracies and mistakes in English, I am just starting to familiarize myself with programming))
There is my variant:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#define SIZE 20
int main(void) {
system("chcp 1251");
char str[SIZE][SIZE], (*pstr)[SIZE];
pstr = str;
char* pcode;
int kst;
printf("Specify the number of lines you want to enter: ");
scanf_s("%d", &kst);
getchar();
while (kst > SIZE)
{
printf("You have exceeded the allowed value (the number of lines must be less than 20): ");
scanf_s("%d", &kst);
getchar();
}
while (kst < 1)
{
printf("You entered a number that is too small, try entering a number between 1 and 20:");
scanf_s("%d", &kst);
getchar();
}
int isXDigit;
printf("\nEnter the lines:\n\n");
while (pstr < str + kst)
{
isXDigit = 1;
gets_s(*pstr);
for (pcode = *pstr; *pcode != '\0'; pcode++){
if (isxdigit(*pcode) == 0){
**pstr = 0;
break;
}
}
pstr++;
}
printf("\nThe result\n");
unsigned long long sixteen;
for (pstr = str; pstr < str + kst; pstr++)
{
if (**pstr == 0)
printf("16: The error!\n");
else {
sixteen = strtoull (*pstr, NULL, 16);
printf("16: %#020llx | 10: %llu\n", sixteen, sixteen);
}
}
return 0;
}
unsigned long long hexToNum(const char *hexSTR)
{
const char *digits = "0123456789ABCDEF";
const char *found = NULL;
unsigned long long result = 0;
while(*hexSTR)
{
result *= 0x10;
if(found = strchr(digits, toupper((unsigned char)*hexSTR)))
result += found - digits;
else { result = 0; break;}
hexSTR++;
}
return result;
}
Textual representation of a number
“Hexadecimal” and “decimal” (and “octal” and “binary” et cetera) are all textual representations of a number.
That is, we write numbers with a radix, but a number exists independently of any particular representation.
That is why 0xA equals 10 equals 012 equals 0b1010 (hexadecimal, decimal, octal, and binary representations).
Remember in grade school when you were taught digit places? That is because a number is a polynomial representation of a value.
→ 123 equals 100 + 20 + 3
Or, written as a polynomial:
→ 1×102 + 2×101 + 3×100
That 10 is the radix. If we change the radix, the number gets written differently. The following, even though it has the same digits, is a totally different number:
→ 1×162 + 2×161 + 3×160
We can see this by doing the math.
3×160 is 3
2×161 is 32
1×162 is 256
256 + 32 + 3 is 291
Dissecting a number to a polynomial representation with radix
To get the least-significant digit of a number, you simply take the remainder of dividing it by the radix:
→ 123 ÷ 10 is 12 with a remainder of 3
You can repeat this process to get every digit in the given radix:
→ 12 ÷ 10 is 1 with a remainder of 2
→ 1 ÷ 10 is 0 with a remainder of 1
So the digits, radix 10, of 123 are, least-significant to most-significant, 3, 2, and 1. We write this as 123.
Suppose we take a radix of 16?
→ 123 ÷ 16 is 7 with a remainder of 11 (which we write as B)
→ 7 ÷ 16 is 0 with a remainder of 7
So the hexadecimal (radix == 16) value of 123 is 7B.
Suppose we take a radix of 8?
→ 123 ÷ 8 is 15 with remainder 3
→ 15 ÷ 8 is 1 with remainder 7
→ 1 ÷ 8 is 0 with remainder 1
So the octal (radix == 8) value of 123 is 173.
In C the operators for getting the quotient and remainder are / and %:
42 / 10 is 4 (quotient)
42 % 10 is 2 (remainder)
Building a number from a polynomial representation with radix
If you are given a textual number representation and wish to build that into an actual numeric value, you only need to know the radix and have access to multiplication and addition.
For example, given 2 7 B:
0 * 16 + 2 → 0 + 2 → 2
2 * 16 + 7 → 32 + 7 → 39
39 * 16 + 11 → 624 + 11 → 635
Indeed this is correct: The hexadecimal representation of 635 is 27B. Said another way, the decimal representation of 0x27B is 635.
Functions!
We can make ourselves functions both to build and dissect polynomial text representations.
int hex_to_int( const char * text );
void int_to_hex( int number, char result[] );
Digit symbols
One thing to be aware of is the number of digit symbols available to a given radix.
For decimal we use the digit symbols 0 through 9.
For octal we only use the digit symbols 0 through 7.
For binary we only need 0 and 1.
But we don’t have enough Arabic digit symbols for hexadecimal, which needs 16 digit symbols. So we just start using the alphabet:
→ 0 1 2 3 4 5 6 7 8 9 A B C D E F
Converting to hex is easy. Just use an array:
char digits[] = "0123456789ABCDEF";
To output the digit symbol for digit 13, just use the array:
printf( "%c", digits[13] ); // prints "D"
Going the other way is a little trickier. I recommend you make yourself a little function:
int hex_digit_to_value( int digit )
{
if ((digit >= '0') and (digit <= '9')) return (digit - '0');
if ((digit >= 'A') and (digit <= 'F')) return (digit - 'A') + 10;
if ((digit >= 'a') and (digit <= 'f')) return (digit - 'a') + 10;
return 0; // can't happen? maybe return -1?
}
I have these variables:
int dividend;
int divider;
And I have the function :
Divisibility7 (int num);
Those two variables will be at the main function, and the user will be asked to enter the dividend and divider, but in case the user enter the divider 7, then, the function above will be called.
The problem is that I have to follow specific criteria to do this. So let's say the user will enter with the dividend 7203. This happen :
I. Get the last digit of the number.
Last digit: 3
Ii. Multiply the last digit by 2
3 x 2 = 6
Iii. Get the value of the initial number, without the last digit.
720
Iv. Subtract the initial value without the last digit from the multiplication result.
fabs (720 - 6) = 714
V. Repeat the process until the result is a value less than or equal to 70
Vi. Compare the result with the table of contents (0, 7, 14, 21, 28, 35, 42, 49, 54, 63, 70) for
Determine whether or not the number is divisible by 7
Code :
int res;
int x;
int y;
int Divisibility7(int num) {
int res;
int x;
int y;
int z;
while(num > 70) {
x = num % 10; // get the last digit from the number
y = x * 2; // multiply the last digit by 2;
z = num/10; // get the first digits from the number
fabs(z - y); // subtract the first digits with the last digits;
}
}
In the part of the while, the final fabs(z-y) returns what I want, to be the first digits subtracting the last number, but the problem is that the while stop there, I have to do something to make this while go till 70 or less.
PS : I need to check if the final number from the iterations, it's a number multiplied by 7, how can I do that ? And I can't use mod for this.
You have not changed num in your while loop . Also you do no return the value . Hope the following code will be ok for you .
int Divisibility7(int num) {
int res,x,y,z;
while(num > 70) {
x = num % 10; // get the last digit from the number
y = x * 2; // multiply the last digit by 2;
z = num/10; // get the first digits from the number
num = abs(z - y); // subtract the first digits with the last digits;
}
if(num == 0 || num == 7 || num == 14 || num == 21 || num == 28 || num == 35 || num == 42 || num == 49 || num == 54 || num == 63 || num == 70) {
return 1;
}
else {
return 0;
}
}
Not sure, but I think this is what are you trying to do:
int main (void)
{
int number, lastDigitMultiplied;
scanf("%d", &number);
while(number > 70){
//get the last digit and multiply it by 2
lastDigitMultiplied = (number % 10) * 2;
//subtract the initial value without the last digit from the multiplication result.
number = number / 10 - lastDigitMultiplied;
}
if(abs(number) % 7 == 0)
printf("The result is %d and it is a multiple of 7", number);
else
printf("The result is %d and it is not a multiple of 7", number);
return 0;
}
for divisibility against 7, if you have a positive large bigint already formatted as a string, don't waste time with the regular method doing it 1 digit at a time.
powers of 10, mod 7, repeats every 6 rounds :
10^1 % 7 = 3 10^7 % 7 = 3 10^13 % 7 = 3
10^2 % 7 = 2 10^8 % 7 = 2 10^14 % 7 = 2
10^3 % 7 = 6 10^9 % 7 = 6 10^15 % 7 = 6
10^4 % 7 = 4 10^10 % 7 = 4 10^16 % 7 = 4
10^5 % 7 = 5 10^11 % 7 = 5 10^17 % 7 = 5
10^6 % 7 = 1 10^12 % 7 = 1 10^18 % 7 = 1
meaning, the effects of the digits mod 7 stay identical as long as they're in chunks of 6 digits at a time.
the largest multiple of 6-digits supported by double precision FP to full integer precision would be 12-digits at a time.
So the way to do it is to right-align the digits by padding leading edge zeros to ensure string length is a multiple of 12. Then simply add the digits onto each other, performing a single mod % 7 operation once every 9000 or so rounds of the addition loop
—- (that's when you run up against 2^53 limit; 9007 rounds if u wanna be pedantic about it)
example :
x = 71400535477047763120175175402859619447790
02233464423375355339031113233806609150957
x % 7 = 4
now try summing up chunks of 12 :
007140053547704776312017517540285961944779
002233464423375355339031113233806609150957
007140053547 7140053547
704776312017 711916365564
517540285961 1229456651525
944779002233 2174235653758
464423375355 2638659029113
339031113233 2977690142346
806609150957 3784299293303
----------------------------
3784299293303 % 7 = 4
it works exactly the same for any multiples of 6 : e.g. 6, 18, 24, and 30 --
00714005354770477631201751754
02859619447790022334644233753
55339031113233806609150957
312017 312017
517540 829557
285961 1115518
944779 2060297
002233 2062530
464423 2526953
375355 2902308
339031 3241339
113233 3354572
806609 4161181
150957 4312138
007140 4319278
053547 4372825
704776 5077601
----- -------
_ 5077601 % 7 = 4
00000000714005354770477631201
75175402859619447790022334644
23375355339031113233806609150957
464423375355339031 464423375355339031
113233806609150957 577657181964489988
000000007140053547 577657189104543535
704776312017517540 1282433501122061075
285961944779002233 1568395445901063308
---------------------------------------
1568395445901063308 % 7 = 4
00000000000000714005354770477
63120175175402859619447790022
33464423375355339031113233806
609150957
339031113233806609150957 339031113233806609150957
000000000000007140053547 339031113233813749204504
704776312017517540285961 1043807425251331289490465
944779002233464423375355 1988586427484795712865820
---------------------------------------------------
1988586427484795712865820 % 7 = 4
000000007140053547704776312017517
540285961944779002233464423375355
339031113233806609150957
000000007140053547704776312017 7140053547704776312017
517540285961944779002233464423 517540293101998326707009776440
375355339031113233806609150957 892895632133111560513618927397
892895632133111560513618927397 % 7 = 4
Can anyone explain to me how does this loop works? I understand that the first operator counts its remainder, the second counts its division result, but I can't understand how does it sum them using the loop? Here's the code:
// Calculate the sum of the digits of the number N.
int N, S, Z;
S = 0;
printf("Input N\n");
scanf("%d", &N);
while(N != 0) {
Z = N % 10;
N = N / 10;
S = S + Z;
}
printf("Sum = %d\n", S);
This while loop adds all the digit of your number referred in by N. It add's all the digit by taking remainder of number when divided by 10. And everytime, it eliminates the last digit of the number. So if your number is 326, it will work like:
326 != 0
Z = 6
N = 32
S = 6
32 != 0
Z = 2
N = 3
S = 8
3 != 0
Z = 3
N = 0
S = 11
0 == 0 come out of loop
print value of S i.e. 11
It's basically a sum of digits of an integer number.
Example:
input ==> 1234
output ==> 4+ 3+ 2 + 1 = 10
Code Break down:
Initialize S [sum] to 0.
Loop:
Z = N % 10; , store the remainder of N after %10 into Z.
N = N / 10; , divide the contents on N by 10 and store the result back in N.
S = S + Z;, sum the content of S with the value in Z.
after that, check the modified value of N is 0 or not. If not, continue [1,2,3..)
Suggestion:
Always check the success of scanf("%d", &N);. If by any chance, scanf() fails, your code is trying to access uninitialized variable N, which may very well lead to undefined behaviour.
The loop will execute until the n value become zero. For example
N=123
Then the first time values of the variables is
Z:3 : N:12 : S:3
Second time
Z:2 : N:1 : S:5
Third time
Z:1 : N:0 : S:6
Finally the answer of S will be 3+2+1=6.
Let's for a example take 657:
Z = N % 10; // This line will store 7 in Z
N = N / 10; // this line will convert N to 65
S = S + Z; // and finally this line will add 0+7
How to check if a int var contains a specific number
I cant find a solution for this. For example: i need to check if the int 457 contains the number 5 somewhere.
Thanks for your help ;)
457 % 10 = 7 *
457 / 10 = 45
45 % 10 = 5 *
45 / 10 = 4
4 % 10 = 4 *
4 / 10 = 0 done
Get it?
Here's a C implementation of the algorithm that my answer implies. It will find any digit in any integer. It is essentially the exact same as Shakti Singh's answer except that it works for negative integers and stops as soon as the digit is found...
const int NUMBER = 457; // This can be any integer
const int DIGIT_TO_FIND = 5; // This can be any digit
int thisNumber = NUMBER >= 0 ? NUMBER : -NUMBER; // ?: => Conditional Operator
int thisDigit;
while (thisNumber != 0)
{
thisDigit = thisNumber % 10; // Always equal to the last digit of thisNumber
thisNumber = thisNumber / 10; // Always equal to thisNumber with the last digit
// chopped off, or 0 if thisNumber is less than 10
if (thisDigit == DIGIT_TO_FIND)
{
printf("%d contains digit %d", NUMBER, DIGIT_TO_FIND);
break;
}
}
Convert it to a string and check if the string contains the character '5'.
int i=457, n=0;
while (i>0)
{
n=i%10;
i=i/10;
if (n == 5)
{
printf("5 is there in the number %d",i);
}
}
How to count total number of digits from a given positive number without looping in C?
For integers, take the log10 of the number, round down, and add one.
TEST:
#include <math.h>
#include <stdio.h>
int
num_digits(unsigned long number)
{
return (int)(floor(log10((double)number)) + 1.0);
}
int
main(int argc, char **argv)
{
unsigned long test_numbers[] = {
1, 9, 10, 99, 100, 999, 1000, 9999, 10000, 99999, 100000, 999999,
123456789ul,
999999999ul,
0
};
unsigned long *ptr;
for(ptr = test_numbers; *ptr; ptr++)
{
printf("Number of digits in %lu: %d\n", *ptr, num_digits(*ptr));
}
return 0;
}
Output:
Number of digits in 1: 1
Number of digits in 9: 1
Number of digits in 10: 2
Number of digits in 99: 2
Number of digits in 100: 3
Number of digits in 999: 3
Number of digits in 1000: 4
Number of digits in 9999: 4
Number of digits in 10000: 5
Number of digits in 99999: 5
Number of digits in 100000: 6
Number of digits in 999999: 6
Number of digits in 123456789: 9
Number of digits in 999999999: 9
One possible solutions, assuming 16-bit integer values and logical expressions evaluating to 0 or 1. You could replace the conditions with (u > 99) ? 1 : 0 if you're worried about portability.
int digits( unsigned u)
{
return 1 + (u > 9) + (u > 99) + (u > 999) + (u > 9999);
}
Two solutions for you!
int digit_count(unsigned int n)
{
if (n < 10)
return 1;
else
return (1 + digit_count(n / 10));
}
and
unsigned int n = 50;
int i = 0;
HACK:
i++;
if (n < 10)
{
printf("Digits: %d\n", i);
}
else
{
n /= 10;
goto HACK;
}
Don't hate me for the last one :(
return snprintf(0, 0, "%d", num);