题目:颠倒整数
2015-08-19 19:53
423 查看
将一个整数中的数字进行颠倒,当颠倒后的整数溢出时,返回 0 (标记为 32 位整数)。
您在真实的面试中是否遇到过这个题?
Yes
哪家公司问你的这个题?
Airbnb
Alibaba
Amazon Apple
Baidu Bloomberg
Cisco Dropbox
Ebay Facebook
Google Hulu
Intel Linkedin
Microsoft NetEase
Nvidia Oracle
Pinterest Snapchat
Tencent Twitter
Uber Xiaomi
Yahoo Yelp
Zenefits
感谢您的反馈
样例
给定
给定
标签 Expand
整数
public class Solution {
/**
* @param n the integer to be reversed
* @return the reversed integer
*/
public int reverseInteger(int n) {
// Write your code here
int na[] = new int[1000];
if(n==0) return n;
long res = 0;
if(n>0){
int k = 0;
while(n>0){
na[k++] = n%10;
n = n/10;
}
int x = 0;
while(x<k){
res = res*10 + na[x++];
if(res>Integer.MAX_VALUE){
return 0;
}
}
}else if(n<0){
int y = 0-n;
int k = 0;
while(y>0){
na[k++] = y%10;
y = y/10;
}
int x = 0;
while(x<k){
res = res*10 + na[x++];
if(res>Integer.MAX_VALUE){
return 0;
}
}
res = 0-res;
if(res<Integer.MIN_VALUE){return 0;}
}
return (int)res;
}
}
优化后的代码
public class Solution {
/**
* @param n the integer to be reversed
* @return the reversed integer
*/
public int reverseInteger(int n) {
// Write your code here
if(n==0) return n;
long res = 0;
while(n!=0){
int x = n%10;
res = res*10+x;
while(res>Integer.MAX_VALUE||res<Integer.MIN_VALUE){
return 0;
}
n = n/10;
}
return (int)res;
}
}
您在真实的面试中是否遇到过这个题?
Yes
哪家公司问你的这个题?
Airbnb
Alibaba
Amazon Apple
Baidu Bloomberg
Cisco Dropbox
Ebay Facebook
Google Hulu
Intel Linkedin
Microsoft NetEase
Nvidia Oracle
Pinterest Snapchat
Tencent Twitter
Uber Xiaomi
Yahoo Yelp
Zenefits
感谢您的反馈
样例
给定
x = 123,返回
321
给定
x = -123,返回
-321
标签 Expand
整数
public class Solution {
/**
* @param n the integer to be reversed
* @return the reversed integer
*/
public int reverseInteger(int n) {
// Write your code here
int na[] = new int[1000];
if(n==0) return n;
long res = 0;
if(n>0){
int k = 0;
while(n>0){
na[k++] = n%10;
n = n/10;
}
int x = 0;
while(x<k){
res = res*10 + na[x++];
if(res>Integer.MAX_VALUE){
return 0;
}
}
}else if(n<0){
int y = 0-n;
int k = 0;
while(y>0){
na[k++] = y%10;
y = y/10;
}
int x = 0;
while(x<k){
res = res*10 + na[x++];
if(res>Integer.MAX_VALUE){
return 0;
}
}
res = 0-res;
if(res<Integer.MIN_VALUE){return 0;}
}
return (int)res;
}
}
优化后的代码
public class Solution {
/**
* @param n the integer to be reversed
* @return the reversed integer
*/
public int reverseInteger(int n) {
// Write your code here
if(n==0) return n;
long res = 0;
while(n!=0){
int x = n%10;
res = res*10+x;
while(res>Integer.MAX_VALUE||res<Integer.MIN_VALUE){
return 0;
}
n = n/10;
}
return (int)res;
}
}
相关文章推荐
- JDBC简介(2)
- mvn test 整工程测试解决方案(基于junit.framework)
- Java内存区域划分、内存分配原理
- [Java] switch-case 当中的变量定义
- VC++深入详解——16章:线程同步,事件对象
- UIScrollView
- Eclipse下用Maven搭建SpringMvc+MyBatis
- 设置字体、字号等格式属性
- HDU 2006
- 题目:链表插入排序
- 最近点对问题
- 告诉一个远程团队协作的故事
- ioc开发学习 --简易计时器 (基于iPhone5屏幕尺寸开发)
- FTP上传网站操作过程,自己看
- memcached--高速存储服务
- 题目:链表划分
- 题目:链表倒数第n个节点
- PAT-PAT (Advanced Level) Practise 1006. Sign In and Sign Out (25) (简单题)【一星级】
- 当你访问淘宝的时候,发生了什么?
- bzoj-3669 魔法森林