Microsoft Interview Question
SDETsTeam: Cloud
Country: United States
int ConvertStrToInt(string inputStr)
{
int num = 0;
char[] inputCharArray = inputStr.ToCharArray();
foreach (char ch in inputCharArray)
{
num = num * 10 + (ch - '0');
}
return num;
}
public static int ConvertToInteger(string number)
{
int sign = 1;
int returnValue = 0;
foreach (var digit in number)
{
if (digit == '+') continue;
if (digit == '-')
{
sign = -1;
continue;
}
if (digit < '0' || digit > '9')
throw new ArgumentException("String cannot have numbers!");
returnValue = (returnValue * 10) + (digit - '0');
}
return returnValue * sign;
}
private int parseNumber(String unparsedNumber) {
final char[] unparsedNumberCharacters = unparsedNumber.toCharArray();
int parsedNumber = 0;
int currentPlace = 1;
for (int i = (unparsedNumberCharacters.length - 1); i >= 0; i--) {
parsedNumber += Character.getNumericValue(unparsedNumberCharacters[i]) * currentPlace;
currentPlace *= 10;
}
return parsedNumber;
}
int convert_to_num(char *arr)
{
int num = 0;
int len = 0;
int i =1;
int is_negative = 0;
char *tmp = arr;
if(*tmp)
{
while(*tmp++) /* len of string*/
len++;
tmp = arr;
if(*tmp == '-') {
len = len -1; /* first char is a sign for -ve */
is_negative =1;
tmp = tmp + len;
}
else
{
tmp = tmp + (len -1); /* To last char in the list */
}
while(len--) {
if(('0' <= *tmp) && ('9' >= *tmp))
{
num = num + ((*tmp - '0')*i);
tmp--;
i=i*10;
}
else
{
return 0;
}
}
}
if(num && is_negative) {
num = ~num+1;
}
return num;
}
public class stringToInteger {
public static void main(String[] args) {
int y=1;
int number = 0;
int start = 0;
int sign =1;
String str = "9000";
if(str.charAt(0) == '+'){
start++;
sign = 1;
}
else if(str.charAt(0) == '-'){
start++;
sign = -1;
}
for(int i=str.length()-1; i>=start;i--){
char c = str.charAt(i);
number = number + ((c-48)*y);
y*=10;
}
number *= sign;
System.out.println(number);
}
}
Assume if the input is not a numeric string then throw exception:
private int stringToInt(String s){
if(isNumeric(s)) {
long maxInt = Integer.MAX_VALUE;
long minInt = Integer.MIN_VALUE;
long stringValue = Long.parseLong(s);
if (stringValue > maxInt || stringValue < minInt) {
throw new ArithmeticException("String value : " + s + " is beyond integer range.");
} else {
return Integer.parseInt(s);
}
}
else{
throw new NumberFormatException("The String input is not valid.");
}
}
private boolean isNumeric(String s){
for(int i = 0; i<s.length(); ++i){
try{
Integer.parseInt(Character.toString(s.charAt(i)));
}
catch(NumberFormatException e){
return false;
}
}
return true;
}
- m@}{ January 24, 2015