Utils

string to int
// no special include statement required

int num = stoi("23");

// num is 23 now

int to string
// no special include statement required

string s = to_string(12345);

// s is "12345" now
int to char
// no special include statement required

char itoc(int number) {
   return char('0' + number);
}

char c = itoc(5);

// c is '5' now

char to int
// no special include statement required

int ctoi(char c){
    return c - '0';
}

int i = ctoi('6');

// i is 6 now
is small case char (a-z) ?
bool isSmallCaseChar(char c){
  return islower(c);
}

isSmallCaseChar('a') // true
isSmallCaseChar('z') // true
isSmallCaseChar('G') // false
isSmallCaseChar('0') // false
isSmallCaseChar('9') // false
isSmallCaseChar('%') // false
isSmallCaseChar('?') // false
is upper case char (A-Z) ?
bool isUpperCaseChar(char c){
  return isupper(c);
}

isUpperCaseChar('a') // false
isUpperCaseChar('z') // false
isUpperCaseChar('A') // true
isUpperCaseChar('G') // true
isUpperCaseChar('0') // false
isUpperCaseChar('9') // false
isUpperCaseChar('%') // false
isUpperCaseChar('?') // false
is digit ?
#include <cctype>

bool result = isdigit('6');
// result is true

bool result = isdigit('g');
// result is false
is alphaNumeric ?
isalnum('a') // true
isalnum('z') // true
isalnum('G') // true
isalnum('0') // true
isalnum('9') // true
isalnum('%') // false
isalnum('?') // false
get ascii value of character
// no special include statement required

int getAsciiValue(char c){
	return int(c);
}

getAsciiValue('a')      // 97
getAsciiValue('D') 	// 68
getAsciiValue('5')      // 53 
getAsciiValue('\n')     // 10

gcd
// GCD aka HCF
int gcd(int a, int b){
    if(a < b) return gcd(b,a);

    if(b == 0) return a;

    return gcd(b, a%b);
}
NCR (i.e. N-choose-R)
// N-choose-R
int NCR(int N, int R){
    double ans = 1;
    R = min(R, N-R);
    for (int numer=N-R+1, denom = 1; denom <= R; numer++,denom++){
        ans = (ans * numer) / denom;
    }
    return (int)ans;
}

Last updated