Your task is to calculate the number of bit strings of length .
For example, if , the correct answer is , because the possible bit strings are 000, 001, 010, 011, 100, 101, 110, and 111.
Example:
Input: n = 3
Output: 8
Approach
Java
public class BitString {public static void main(String[] args) {long n = 3;System.out.println(power(2, n));}static int MOD = (int) 1000000007;static long power(long a, long n) {long res = 1;while (n > 0) {if (n % 2 == 1)res = ((res) % MOD * (a) % MOD) % MOD;a = ((a) % MOD * (a) % MOD) % MOD;n /= 2;}return res;}}
C++
#include <bits/stdc++.h>using namespace std;#define MOD 1000000007long long power(long long a, long long n){long long res = 1;while (n){if (n & 1)res = ((res) % MOD * (a) % MOD) % MOD;a = ((a) % MOD * (a) % MOD) % MOD;n /= 2;}return res;}int main(){long long n = 3;cout << power(2, n) << "\n";return 0;}
No comments:
Post a Comment