码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode -- Day 45

时间:2015-08-17 11:25:12      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

Reverse num/word/bits

最近回国了 有点懒

Question 1

Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Be careful about some interesting cases. i.e.negative number, overflow case.

 1     public int reverse(int x) {
 2         if (x >= -9 && x <= 9){
 3             return x;
 4         }
 5         
 6         boolean isNeg = false;
 7         if (x < 0){
 8             isNeg = true;
 9             x = 0 - x;
10         }
11         
12         double result = 0;
13         
14         while(x > 0){
15             result = result * 10 + x % 10;
16             x = x / 10;
17         }
18         
19         if (isNeg){
20             return -result < Integer.MIN_VALUE ? 0 : -(int)result;
21         }
22         else{
23             return result > Integer.MAX_VALUE ? 0 : (int)result;
24         }
25

Question 2

Reverse Words in a String

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

I use split to change it an word array, or you can use toCharArray() to change it to char array. 

 

 1     public String reverseWords(String s) {
 2         StringBuffer result = "";
 3         String[] array = s.split(" ");
 4         for (int i = array.length - 1; i >= 0; i --){
 5             String temp = array[i].trim();
 6             if (temp.equals("") == false){
 7                 if (i != array.length - 1){
 8                     result += " " + temp;
 9                 }
10                 else{
11                     result += temp;
12                 }
13             }
14         }
15         return result.trim();
16     }

 

 

 

Leetcode -- Day 45

标签:

原文地址:http://www.cnblogs.com/timoBlog/p/4735861.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!