get each digit of a number

[TOC]

output each number in one decimal place

int a = 123;
printf("%d %d %d",a/100,a/10%10,a%10);

Extending to the more general case, each digit of a decimal digit should be
$$
\frac a{10^n} %10 , divided by the weight of the current digit
$$

If it is K base, it should be:
$$
\frac a{K^n} %K , divided by the weight of the current bit
$$

Variant problem: the base system is not unified

1058.A+B in Hogwarts

The meaning of the title is roughly, there is a currency, 29 Knut is equal to 1 Sickle, 1 Sickle is equal to 17 Galleon, how to convert Kunt up to other units

int a = 123;
printf("%d %d %d",a/(29*17),a/17%29,a/29);

The weights of the three digits are **29*17, 29, 1** respectively, so:

printf("%d %d %d",a/(29*17),a/29%17,a%29);

The first one doesn't need to be %29 because there are no other units on it

Variant problem: take any consecutive digits of a number

Take 12, 345, 678 of 12345678

The idea is roughly as follows: the original number can be divided into three digits, (12)(345)(678) , each bracket is equivalent to one digit, and the base of the number is 1000. According to the previous principle, you can write out:

printf("%d %d %d",a/1000000,a/1000%1000,a%1000);

So, for example the following problem, there is a simpler solution
1001.A+B Format

#include <cstdio>
#include <cstring>
int main(){
    int a,b;
    scanf("%d %d",&a,&b);
    int c = a + b;
    if(c < 0){
        printf("-");
        c *= -1;
    }
    if(c >= 1000000){
        printf("%d,%03d,%03d",c/1000000,c/1000%1000,c%1000);
    }else if(c >= 1000){
        printf("%d,%03d",c/1000,c % 1000);
    }else{
        printf("%d",c);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325523630&siteId=291194637