49:题目描述
将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。
输入描述:
输入一个字符串,包括数字字母符号,可以为空
输出描述:
如果是合法的数值表达则返回该数字,否则返回0
示例1
输入
+2147483647
1a33
输出
2147483647
0
class Solution {
public:
bool g_flag=true;//true - ok false-data error
int StrToInt(string str) {
if(str.empty())
{
g_flag=false;
return 0;
}
bool flag=true;//true - positive false - negative
long long sum=0;
int i=0;
while(str[i]==' ')
++i;//过滤空格
if(str[i]=='+')
++i;
else if(str[i]=='-')
{
flag=false;
++i;
}
for(;str[i]!='\0';++i)
{
if(str[i]>'9' || str[i]<'0')
{
g_flag=false;
return 0;
}
sum=10*sum+str[i]-'0';
if((flag && (sum>0x7fffffff)) || (!flag && (sum>0x80000000)))
{
g_flag=false;
return 0;
}
}
return flag?sum:-1*sum;
}
};
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.g_flag=True
def StrToInt(self, s):
if s=="":
self.g_flag=False
return 0
i=s_all=0
while s[i]==' ':
i+=1
flag=True
if(s[i]=='+'):
i+=1
elif s[i]=='-':
i+=1
flag=False
for j in range(i,len(s))://python中字符串结尾不是\0
if s[j]>'9' or s[j]<'0':
self.g_flag=False
return 0
s_all=s_all*10+int(s[j])
if ((flag==True) and (s_all>0x7fffffff)) or ((flag==False) and (s_all>0x80000000)):
self.g_flag=False
return 0
return s_all if flag else -1*s_all
# write code here
50.题目描述
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
class Solution {
public:
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
bool duplicate(int numbers[], int length, int* duplication) {
if(numbers==NULL || length<=0)
return false;
bool *hash=new bool[length]();
for(int i=0;i<length;++i)
{
if(hash[numbers[i]]==true)
{
*duplication=numbers[i];
return true;
}
hash[numbers[i]]=true;
}
return false;
}
};
class Solution {
public:
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
bool duplicate(int numbers[], int length, int* duplication) {
if(numbers==NULL || length<=0)
return false;
map<int,int>data;
for(int i=0;i<length;++i)
{
++data[numbers[i]];
if(data[numbers[i]]==2)
{
*duplication=numbers[i];
return true;
}
}
return false;
}
};
# -*- coding:utf-8 -*-
class Solution:
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(self, numbers, duplication):
if len(numbers)==0:
return False
for i in numbers:
if numbers.count(i)==2:
duplication[0]=i
return True
return False
# write code here