在上一期的[DLdigest-7] 每日一道算法中,题目是给定一个整数,然后将它每个位上的数字颠倒过来重新组成一个整数。
需要注意的就是输入的整数类型为32位有符号型,输出是否有溢出需要考虑,一旦溢出就输出0。在程序中判断一个数是否溢出的办法就是把这个数乘以10然后再除以10,如果可以正确复原,那么表示没有溢出,否则就是发生了溢出。
class Solution {
public:
int reverse(int x) {
int result=0;
int flag=x>0?1:-1;
x = fabs(x);
while(x>0) {
int tmp = result*10 + x%10;
if(tmp/10 != result)
return 0;
result = tmp;
x = x/10;
}
return flag*result;
}
};
int main() {
int s1=120300;
int s2=1534236469;
int s3=1563847412;
Solution s;
cout<<s1<<"-->"<<s.reverse(s1)<<endl;
cout<<s2<<"-->"<<s.reverse(s2)<<endl;
cout<<s3<<"-->"<<s.reverse(s3)<<endl;
return 0;
}
运行结果:
120300-->3021
1534236469-->0
1563847412-->0
每日一道算法——String to Integer
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
spoilers alert… click to show requirements for atoi.
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
近期将以NLP领域论文分享及注意力机制的代码实践为主,每天一道算法会保持更新。欢迎大家留言分享深度学习知识或交流每日一道算法的思路,本期算法的解决方法将在下一期中讲解。
你可能会感兴趣的文章有:
[DLdigest-3] Python中让你无法预测的“是”
动态层归一化(Dynamic Layer Normalization)
详述DeepMind wavenet原理及其TensorFlow实现
Layer Normalization原理及其TensorFlow实现
Batch Normalization原理及其TensorFlow实现
Maxout Network原理及其TensorFlow实现
Network-in-Network原理及其TensorFlow实现
如何基于TensorFlow实现ResNet和HighwayNet
深度学习每日摘要|坚持技术,追求原创