0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【C言語】大きい整数型long longを使う / 流動的な桁数の0埋め【備忘録】

Last updated at Posted at 2022-10-04

大きい整数は64ビットの整数型long longを使う

整数型intはサイズが32ビットしかないので、整数の桁が大きくなるときは別の変数型を使います。
今回はlong long型(64ビット)を使うとうまくいきました。

問題:
標準入力から二つの整数aとbが入力されます。
aを左にbビットシフトした結果を一行で出力してください。
(TechFULより引用)

long long型の変換指定は %lld と書く

#include <stdio.h>
int main(void)
{
    long long a, b, i;
    scanf("%lld %lld", &a, &b);

    a = a << b;

    printf("%lld\n", a);
    return 0;
}

2022/10/5実施
参照先:TechFUL


流動的な桁数の0埋めをする

桁数が定まっていないときのゼロ埋めのやり方です。
桁数が(例えば8桁と)決まっている場合は"%08d"と書きます。
しかし今回は桁数が変数nで与えられるまで分からないので*を使いました。

問題(概要):
ふたつの同じ桁数の二進数a, bが与えられる。
桁数nも与えられる。
a, bをOR演算したものを出力したい。
(元の問題はTechFULより)

printf("%0*d", 0埋めしたい桁数, 数値);

-をつけると左詰めにできる

参考にした記事:
https://marycore.jp/prog/c-lang/left-right-zero-padding/

#include <stdio.h>
#include <stdlib.h>

int binaryToDecimal(int);//2進数を10進数に変換する関数のプロトタイプ宣言
int decimalToBinary(int);//10進数に2進数に変換する関数のプロトタイプ宣言

int main()//メインの関数
{
    int n, a, b, answer, i;
    scanf("%d %d %d", &n, &a, &b);

    //aとbを10進数に変換する
    a = binaryToDecimal(a);
    b = binaryToDecimal(b);

    //OR演算をする
    answer = a | b;
    answer = decimalToBinary(answer);

    //答えを出力する
    if (answer == 0) {
        for (i = 0; n > i; i++) {
            printf("%d", answer);
        }
        printf("\n");
    }
    else {
        printf("%0*d\n", n, answer);
    }

    return 0;
}

int binaryToDecimal(int bi) {//二進数を10進数に
    int temp = 0;
    int base = 1;
    while (bi > 0) {
        temp += (bi % 2) * base;
        bi -= bi % 2;
        bi /= 10;
        base *= 2;
    }
    return temp;
}

int decimalToBinary(int de) {//10進数を二進数に
    int temp = 0;
    int base = 1;
    while (de > 0) {
        temp += (de % 2) * base;
        de -= (de % 2);
        de /= 2;
        base *= 10;
    }
    return temp;
}

2022/10/4実施
参照先:TechFUL

今の実力ではこれしか思いつきませんでした。
スムーズなコードが書けるようにいつか再チャレンジしたいです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?