In this HackerRank Day 16: Exceptions - String to Integer problem solution Read a string, S, and print its integer value; if S cannot be converted to an integer, print Bad String.


HackerRank Day 16: Exceptions - String to Integer problem solution

Problem solution in Python programming.

#!/bin/python3

import sys


S = input().strip()

try:
  i = int(S)
  print(i)
except:
  print("Bad String")



Problem solution in Java programming.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String S = in.next();
        int s;
        try{
            s = (Integer)Integer.parseInt(S);
            System.out.println(s);
        }catch(NumberFormatException e)
        {
            System.out.println("Bad String");
        }

    }
}




Problem solution in C++ programming.

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>

#include<string>
#include<iomanip>

using namespace std;


int main(){


	try {
		string S;
		cin>>S;
		int val= stoi(S);
		cout << val << endl;
	}catch (const invalid_argument& ia) {
		cout << "Bad String"<<endl;
	}
	return 0;
}



Problem solution in Javascript programming.

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function main() {
    var s = readLine();
    var i=1;
    try {
        
        eval(s); // Fails on NaN
         console.log(s);
            
    } catch (e) {
        console.log( 'Bad String'); 
    }

}