Lets say I have an integer called SIN and the scanf input receives 193456787.
so SIN = 193456787;
What I want to do is add up all the other numbers after the first digit.
So 9 + 4 + 6 + 8 = 27
Can somebody please explain to a beginner how to do this?
Print the number and then sum every other digit
int sum_every_other_digit_after_first(unsigned long long x) {
char buf[sizeof x * CHAR_BIT];
sprintf(buf, "%llu", x);
char *p = buf;
int sum = 0;
while (*p) {
p++; // Skip digit
if (*p) {
sum += *p++ - '0';
}
}
return sum;
}
or as inspired by #PageNotFound
int sum_every_other_digit_after_first(unsigned long long x) {
int esum = 0;
int osum = 0;
while (x > 0) {
esum += x%10;
x /= 10;
if (x == 0) {
return osum;
}
osum += x%10;
x /= 10;
}
return esum;
}
or for fun, a recursive solution
int sum_every_other_digit_after_first_r(unsigned long long x, int esum, int osum) {
if (x >= 100) {
int digit2 = x % 100;
esum += digit2 % 10;
osum += digit2 / 10
return sum_every_other_digit_after_first_r(x / 100, esum, osum);
}
if (x >= 10) {
return esum + x % 10;
}
return osum;
}
sum_every_other_digit_after_first_r(1234567,0,0) --> 12
My solution
#include <stdio.h>
int main()
{
int SIN = 193456787;
int a = 0, b = 0, cnt = 0;
while (SIN > 0) {
if (cnt % 2) b += SIN % 10;
else a += SIN % 10;
cnt++;
SIN /= 10;
}
printf("%d\n", cnt%2 ? b : a);
return 0;
}
Note: Please comment if this is not what you intended, as your question is a little ambigous.
#include <stdio.h>
int main() {
unsigned number;
scanf("%u\n", &number);
unsigned result = 0;
unsigned tmp = number;
unsigned numberOfDigits = 0;
do
numberOfDigits++;
while((tmp /= 10) != 0);
if(numberOfDigits % 2 != 0)
number /= 10;
while(number >= 10) {
result += number % 10;
number /= 100; // Skip two digits
}
printf("%u\n", result);
}
Related
Let say I have two ints
a = 1234
b = 45678
Now I want to "interlace" them into a third int c that looks something like this
c = 415263748 assume the the length of these don't change. So far I've been able to do this:
unsigned interlace(unsigned x, unsigned y) {
unsigned pow = 10;
while(y >= pow)
pow *= 10;
return x * pow + y;
}
You have to get digits one by one. When you say x % 10 you get the least significant digit. When you say x = x /10 you remove the least significant digit. Start doing it for y then keep alternating:
unsigned interlace(unsigned x, unsigned y)
{
//If the parameters order could be inverted...
if(x > y)
{
unsigned z = x;
x = y;
y = z;
}
unsigned ans = y % 10;
y = y/10;
unsigned exponent = 10;
while(y)
{
ans += (x%10)*exponent;
x = x/10;
exponent *= 10;
ans += (y%10)*exponent;
y = y/10;
exponent *= 10;
}
return ans;
}
A slight twist on approach can eliminate the order of parameter issue by handling the interlacing on string representations of the values. This allows a simple way to sew the two numbers together. While strlen() is used here, you can also use snprintf (NULL, 0, "%u", a) and snprintf (NULL, 0, "%u", b) to determine the number of digits in each.
A simple approach interlacing the string representations would be:
#define NUMC 32
unsigned interlace (unsigned a, unsigned b)
{
char sa[NUMC], sb[NUMC], result[2*NUMC];
size_t lena, lenb, n = 0;
sprintf (sa, "%u", a);
sprintf (sb, "%u", b);
lena = strlen(sa);
lenb = strlen(sb);
if (lena > lenb) {
for (size_t i = 0, j = 0; sa[i]; i++) {
result[n++] = sa[i];
if (sb[j])
result[n++] = sb[j++];
}
result[n] = 0;
return (unsigned)strtoul (result, NULL, 0);
}
for (size_t i = 0, j = 0; sb[i]; i++) {
result[n++] = sb[i];
if (sa[j])
result[n++] = sa[j++];
}
result[n] = 0;
return (unsigned)strtoul (result, NULL, 0);
}
(note: the validations on conversion and length checks greater than zero should be added above. They were intentionally omitted for brevity)
The order of parameters is irrelevant. You can call it as interlace (a, b) or interlace (b, a) and the result will be correct each time.
A short example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUMC 32
unsigned interlace (unsigned a, unsigned b)
{
char sa[NUMC], sb[NUMC], result[2*NUMC];
size_t lena, lenb, n = 0;
sprintf (sa, "%u", a);
sprintf (sb, "%u", b);
lena = strlen(sa);
lenb = strlen(sb);
if (lena > lenb) {
for (size_t i = 0, j = 0; sa[i]; i++) {
result[n++] = sa[i];
if (sb[j])
result[n++] = sb[j++];
}
result[n] = 0;
return (unsigned)strtoul (result, NULL, 0);
}
for (size_t i = 0, j = 0; sb[i]; i++) {
result[n++] = sb[i];
if (sa[j])
result[n++] = sa[j++];
}
result[n] = 0;
return (unsigned)strtoul (result, NULL, 0);
}
int main (void) {
unsigned a = 1234, b = 45678;
printf ("interlaced: %u\n", interlace (a, b));
}
Example Use/Output
$ ./bin/interlace_int
interlaced: 415263748
Another completely different approach, more inline with your original can make use of the div function and the div_t struct to automate handling the division and remainder. You can use the snprintf (NULL, 0, "%u", var); function to determine the number of digits so you can swap parameters if necessary.
A short example is:
#include <stdio.h>
#include <stdlib.h>
unsigned interlace (unsigned a, unsigned b)
{
unsigned result = 0, mult = 1;
div_t da = { .quot = a }, db = { .quot = b };
if (snprintf (NULL, 0, "%u", b) > snprintf (NULL, 0, "%u", a)) {
div_t tmp = da;
da = db;
db = tmp;
}
do {
da = div (da.quot, 10);
result += da.rem * mult;
mult *= 10;
if (db.quot) {
db = div (db.quot, 10);
result += db.rem * mult;
mult *= 10;
}
} while (da.quot);
return result;
}
int main (void) {
unsigned a = 1234, b = 45678;
printf ("interlaced: %u\n", interlace (a, b));
}
(note: here again, the order of parameters is irrelevant and you can provide a and b in any order and still arrive at the correct result)
Example Use/Output
$ ./bin/interlace_unsinged
interlaced: 415263748
Let me know if you have further questions. Just another way to skin the interlace cat.
This is not exactly what you asked for but maybe you can reuse some of this logic on your function....
OUTPUT:
Interlace 2 numbers as a printf
Enter number a: forty-three
Insert digit : 1234
Enter number b: 45678
Interlaced numbers: 142536478
CODE:
#include <stdio.h>
int main(void){
long int num , num2, temp , factor = 1, factor2 = 1;
puts("Interlace 2 numbers as a printf");
printf("Enter number a: ");
while(!scanf(" %ld",&num)){
while ((temp = getchar()) != '\n' && temp != EOF);
printf("Insert digit : ");
}
printf("Enter number b: ");
while(!scanf(" %ld",&num2)){
while ((temp = getchar()) != '\n' && temp != EOF);
printf("Insert digit : ");
}
temp = num;
while(temp){
temp /= 10;
factor *= 10;
}
temp = num2;
while(temp){
temp /= 10;
factor2 *= 10;
}
printf("Interlaced numbers: ");
while(factor>1)
{
factor /= 10;
printf("%ld",num/factor);
num %= factor;
if (factor2 > 1)
{
factor2 /= 10;
printf("%ld",num2/factor2);
num2 %= factor2;
}
}
while(factor2>1)
{
factor2 /= 10;
printf("%ld",num2/factor2);
num2 %= factor2;
}
putchar('\n');
return 0;
}
#include <stdio.h>
#include <math.h>
int main(void) {
int a = 1234;
int b = 45678;
int c = 0;
while(a || b)
{
if (b)
{
int m = pow(10, (int)log10(b));
c=c*10 + b/m;
b = b%m;
}
if (a)
{
int m = pow(10, (int)log10(a));
c=c*10+a/m;
a = a%m;
}
}
printf("Result: %d\n", c);
return 0;
}
Output:
Success #stdin #stdout 0s 4692KB
Result: 415263748
IDEOne Link
Appending the last digit of the two numbers alternatively to n * 10(repeated operation), gives you the reverse of the interlace.
Just to help if you are stuck in generating reversed interlace.
unsigned interlace (unsigned x, unsigned y)
{
unsigned n, r;
if( x > y)
{
temp = x;
x = y;
y = temp;
}
n = y % 10;
y = y / 10;
while (x || y) // To Generate reverse of the interlace
{
n = n * 10 + (x % 10);
x /= 10;
n = n * 10 + (y % 10);
y /= 10;
}
r = n % 10;
n = n / 10;
while(n != 0) // reverse it to get the interlaced number
{
r = r * 10 + (n % 10);
n /= 10;
}
return r;
}
I have a problem with a such a task:
Write a program that finds such a pair of numbers x and y that their sum is equal to n. In addition, the pair of numbers should meet the following conditions:
the number x has at least 2 digits,
the number y is one digit less than the number x.
N is from the range <10 ; 10^5>
for number 80, the output should look like this:
79 + 1 = 80
78 + 2 = 80
77 + 3 = 80
76 + 4 = 80
75 + 5 = 80
74 + 6 = 80
73 + 7 = 80
72 + 8 = 80
71 + 9 = 80
I wrote a code that works in most cases but the system rejects the solution when testing the number 100000, because the program does not find such pairs - the test requires 9000 such pairs. I can't understand what's wrong because I think the program is okay. I'd like to ask for some advice.
My code:
#include <stdio.h>
#include <math.h>
int digit_count(int n)
{
int i = 0;
while (n > 0)
{
n /= 10;
i++;
}
return i;
}
int breakdown(int n)
{
long n_digits = digit_count(n), check = 0, count = 1;
long double y_max = pow(10, (n_digits - 1)) - 1, y_min = (pow(10, (n_digits - 2)));
for (int i = (int)y_min; i <= (int)y_max; i++)
{
if (digit_count(n - i) >= 2 && digit_count(i)+1 == digit_count(n - 1))
{
printf("%d + %d = %d %d\n", n - i, i, n, count);
check = 1;
count++;
}
}
if (check == 0)
{
printf("Nothing to show.");
}
return 0;
}
int main(void)
{
unsigned int n = 0;
printf("Podaj N: ");
if (1 != scanf("%u", &n))
{
printf("Incorrect input");
return 1;
}
if (n > 1000000 || n < 10)
{
printf("Incorrect input");
return 1;
}
breakdown(n);
return 0;
}
PS: I forgot to mention that the count variable is here only for debugging
I solved the problem in this way. Now it works for all numbers in the range according to the task.
#include <stdio.h>
#include <math.h>
int digit_count(int n)
{
int i = 0;
while (n > 0)
{
n /= 10;
i++;
}
return i;
}
int breakdown(int n)
{
int n_digits = digit_count(n), check = 0;
double y_max = pow(10, n_digits - 1) - 1;
//int i = 0 instead of i = y_min = (pow(10, (n_digits - 2))
for (int i = 0; i <= (int)y_max; i++)
{
//instead of if (digit_count(n - i) >= 2 && digit_count(i)+1 == digit_count(n - i))
if (digit_count(n - i) >= 2 && digit_count(n - i) == digit_count(i) + 1)
{
printf("%d + %d = %d\n", n - i, i, n);
check = 1;
}
}
if (check == 0)
{
printf("Nothing to show.");
}
return 0;
}
int main(void)
{
unsigned int n = 0;
printf("Podaj N: ");
if (1 != scanf("%u", &n))
{
printf("Incorrect input");
return 1;
}
if (n > 1000000 || n < 10)
{
printf("Incorrect input");
return 1;
}
breakdown(n);
return 0;
}
The posted code checks all the numbers in [10k - 2, 10k - 1 - 1], k beeing the number of digits of n, using the expansive (and wrong) condition
if (digit_count(n - i) >= 2 && digit_count(i)+1 == digit_count(n - 1)) { /* ... */ }
// ^
You can solve the problem avoiding all (or at least most of) those digits counts, by carefully calculating the valid extents of the ranges of the x and y values.
The following is a possible implementation
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
static inline long min_(long a, long b)
{
return b < a ? b : a;
}
static inline long max_(long a, long b)
{
return b < a ? a : b;
}
int digit_count(long n);
// Specilization for integer exponent.
long pow_10_(int exponent);
// A little helper struct
typedef struct range_s
{
long begin, end;
} range_t;
// Shrinks the range of the y values so that all the x = z - y are valid
// (the right nummber of digits and less than z).
range_t find_range(long z, long x_0)
{
range_t y = {max_(1, x_0 / 10), x_0};
range_t x = {x_0, min_(z, x_0 * 10)};
long x_1 = z - y.begin;
if (x_1 < x.begin)
y.end = y.begin;
else if (x_1 >= x.end)
y.begin = min_(z - x.end + 1, y.end);
long x_2 = z - y.end;
if (x_2 > x.end)
y.begin = y.end;
else if (x_2 <= x.begin)
y.end = max_(z - x.begin + 1, y.begin);
return y;
}
long print_sums(long z, range_t y);
long breakdown(long z)
{
int n_digits = digit_count(z); // <- Only once.
long x_0 = pow_10_(n_digits - 1);
// Depending on z, the x values may have the same number of digits of z or
// one less.
long count = 0;
if (n_digits > 2)
{
count += print_sums(z, find_range(z, x_0 / 10));
}
count += print_sums(z, find_range(z, x_0));
return count;
}
int main(void)
{
long n = 0;
if (1 != scanf("%lu", &n))
{
printf("Incorrect input");
return 1;
}
if (n > 1000000 || n < 10)
{
printf("Incorrect input");
return 1;
}
printf("\nCount: %ld\n", breakdown(n));
return 0;
}
int digit_count(long n)
{
int i = 0;
while (n > 0)
{
n /= 10;
i++;
}
return i ? i : 1; // I consider 0 a 1-digit number.
}
long pow_10_(int exponent)
{
if (exponent < 0)
return 0;
long result = 1;
while (exponent-- > 0)
result *= 10;
return result;
}
#define SAMPLES 5
long print_sums(long z, range_t y)
{
for (long i = y.begin; i < y.end; ++i)
#ifndef SHOW_ONLY_SAMPLES
printf("%ld + %ld = %ld\n", z - i, i, z);
#else
if ( i < y.begin + SAMPLES - 1 || i > y.end - SAMPLES )
printf("%ld + %ld = %ld\n", z - i, i, z);
else if ( i == y.begin + SAMPLES )
puts("...");
#endif
return y.end - y.begin;
}
Testable here.
I am trying to solve this tutorial practice question that doesn't have an answer that I can check my code against. The goal is to write a program to display numbers whose digits are 2 greater than the corresponding digits of the entered number. So if the number input is 5656 then the output number should be 7878. I have figured out how to separate each number and add them, but I can't seem to get them to print in a four-digit sequence.
#include <stdio.h>
int main ()
{
int n, one, two, three, four, final;
scanf("%d", &n);
one = (n / 1000);
n = (n % 1000) + 2;
two = (n / 100) + 2;
n = (n % 100) + 2;
three = (n / 10) + 2;
n = (n % 10) + 2;
four = (n / 1) + 2;
n = (n % 1) + 2;
final = (one * 1000) + (two * 100) + (three * 10) + four;
printf("%d", final);
return 0;
}
#include <stdio.h>
int main()
{
int n,a[4], final;
scanf("%d", &n);
for(int i=3;i>=0;i--)
{
a[i]=n%10+2;
n/=10;
}
final = (a[0] * 1000) + (a[1] * 100) + (a[2] * 10) + a[3];
printf("%d", final);
return 0;
}
Below function works with N number of digits.
Idea is to extract each digit from the input number and add its decimal position.
#include <stdio.h>
int power(int x, int y)
{
int res = 1;
for (;y>0;y--)
{
res *=x;
}
return res;
}
int main ()
{
int n;
scanf("%d", &n);
int sum = 0;
int i=0;
while(n>0)
{
sum += ((n%10) +2)*power(10,i);
i++;
n /=10;
}
printf("%d", sum);
return 0;
}
Another idea:
char str[10]; // enough to contain an int as string + 1
char *s = str+sizeof(str); // points to last char + 1
int n;
scanf("%d", &n);
*--s = 0; // terminate the string
while(n) {
*--s = (((n % 10)+2)%10) + '0'; // write a char from the end
n /= 10;
}
printf("%s\n", s);
int a = 5696;
// output is 7818
// ---------Java-----------
// --------solution--------
int first = a/1000+2;
int b = a%1000;
int second = b/100+2;
int c = b%100;
int d = c/10+2;
int third = d/10;
int e = c%10;
int fourth = e+2;
String result = Integer.toString(first)+Integer.toString(second)+Integer.toString(third)+Integer.toString(fourth);
System.out.println(result);
if the user inputs the "value" as 1223445 the output should read as follows:
After change #1: 12235
After change #2: 135
the code is meant to take out two consecutive numbers with the same value. the first loop works but then it stops and I cannot figure why. here is the code:
{
int count;
int y;
int z;
int b;
int c;
int d;
int a;
int ct;
y = 0;
z = 1;
d = 0;
count = 0;
if (value > 0)
while ((z * 10 + z) != (y % 100))
{
y = value % 10 + y * 10;
z = y % 10;
value /= 10;
count = count + 1;
}
value = value * pow(10, count - 2);
y = y / 100;
count = count - 3;
while(y > 0)
{
b = y % 10;
c = pow(10, count);
d = d + c * b;
y = y / 10;
count = count - 1;
}
value = value + d;
ct = 1;
printf("After change #%d: %d\n", ct, value);
a = value;
while (a > 1)
{
if((a % 100) - (a % 10) - (10 * (a % 10)) == 0)
Change(value);
else
a = a / 10;
}
return;
}
Here's a simple solution: (not sure how you want to handle odd numbered repeats e.g. '111', '11111')
public static long strip(long value, long sum) {
if(value==0) return sum;
long tens = value % 100;
long ones = value % 10;
if(ones*10 == tens-ones) {
return strip(value /100, sum);
}
if(sum==0) sum +=(value%10);
else {
long x = (long)Math.ceil((Math.log10(sum)));
sum =(long) (Math.pow(10,x) * ones + sum);
}
return strip(value /10, sum);
}
I am attempting to print integers to the console in C with a few constraints, the most significant of which being that I may only write individual characters to the console as follows:
void my_char(char ch)
}
write(1, &ch, 1);
}
Other constraints include NO predefined methods (printf, log, etc). No recursion. Lastly, I may NOT create an array.
So far I have come up with a method that prints the numbers out perfectly well... backwards.
int main()
{
int i = -345320;
my_int(i);
return 0;
}
void my_int(int x)
{
char *a;
int n;
if(x < 0)
{
x = x * -1;
my_char('-');
}
while(x)
{
n = x % 10;
a = (char*)&n;
my_char(*a + 48);
x /= 10;
}
}
Are there other good ways to approach this or am I at least going in the right direction? I would ideally like to expand this to print an integer in any base I provide, but I need to start here.
I was playing with iterating a pointer over each Byte of the integer but I can't grasp how I would use those character values to re-create the integer.
Any advice is appreciated. I'd much rather receive some insight than just a code solution. I'd also love input on making it more lean.
Here's a general (ugly!) solution following your constraints. It uses the idea I gave in the comment above. It assumes 32-bit ints.
void my_int(int x) {
int n = 1000000000;
if (x == 0) {
my_char('0');
return;
}
if (x == INT_MIN) { // INT_MIN is in limits.h
my_char('-'); my_char('2'); my_char('1');
my_char('4'); my_char('7'); my_char('4');
my_char('8'); my_char('3'); my_char('6');
my_char('4'); my_char('8');
return;
}
if (x < 0) {
x *= -1;
my_char('-');
}
while (n > x) n /= 10;
while (n != 0) {
my_char(x / n % 10 + '0');
n /= 10;
}
}
This should do the trick. It prints the integer forwards.:
void my_int(int x)
{
int temp = 0;
int divFactor = 10;
if(x==0)
{
my_char('0');
return;
}
if(x < 0)
{
x = x * -1;
my_char('-');
}
temp = x;
while((temp /= 10) > 10) {divFactor *= 10;}
for(;divFactor > 0;divFactor /= 10)
{
temp = x;
temp /= divFactor;
my_char(temp + '0');
x -= divFactor * temp;
}
printf("\n done!");
}
int main()
{
int i = -1234001;
my_int(i);
return 0;
}
void my_int(int x)
{
int n;
int copy;
char digit;
// handle 0
if (!x)
{
my_char('0');
return;
}
// emit sign
if(x < 0)
{
x = x * -1;
my_char('-');
}
// count base-10 digits in x, store 10^n in n
n = 1;
copy = x/10; // shorten loop by 1 iteration
while (copy)
{
n *= 10;
copy /= 10;
}
// 'n' is now a digit selector
while (n)
{
digit = x/n;
my_char(digit + '0'); // print the most significant digit
x -= digit*n; // remove the most significant digit from x
n /= 10;
}
}