6. ZigZag Conversion(medium) & 7.Reverse Integer(easy)
題目六:
The string
on a given number of rows like this: (you may want to display this"PAYPALISHIRING"
is written in a zigzag patternpattern in a fixed font for better legibility)
P A H NA P L S I I GY I RAnd then read line by line:
Write the code that will take a string and make this conversion given a number of rows:string convert(string text, int nRows);"PAHNAPLSIIGYIR"
convert("PAYPALISHIRING", 3)
should return"PAHNAPLSIIGYIR"
.
這題無力吐槽,沒什麼意思,讀懂題目就行
示意圖:
規律是一個傾斜的v字形算一組。
具體實現就不給出了,實現思路大同小異,注意一下效率就行。
題目7:
Given a 32-bit signed integer, reverse digits of an integer.
Example 1: Input: 123 Output: 321
Example 2: Input: -123 Output: -321Example 3: Input: 120 Output: 21Note:Assume we are dealing with an environment which could only hold integers
within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
經典的反轉數字,考驗基本功的時候到了!
int reverse(int x) { int result=0; bool is=true; if(x<0) { x=-x; is=false; } while(x>0) { if(result>=((pow(2,32)-1)/10) || result*10+x%10<0) return 0; result=result*10+x%10; x=x/10; } return is?result:-result; }
運行時我已經感覺到判斷溢出那部分有點臃腫
結果beats 14.08%........
我就知道這樣判斷溢出是不行的==
於是改成了if(result>INT_MAX/10 || result*10+x%10<0)(關鍵是我一開始真不知道有這個宏)
發現效率沒變,可能是leetcode把(pow(2,32)-1)優化成了INT_MAX???
一開始的時候我拒絕去掉 || result*10+x%10<0,後來想了想這個條件可能真的沒用,因為如果加上x的首位會溢出的話那x本身也會溢出(INT_MAX是4294 967 295如果溢出首位得大於5,但首位最大是4)
果然去掉之後beats 66.49%
翻了翻其他答案,再優化的話就是
int reverse(int x) { long answer = 0; while (x != 0) { answer = answer * 10 + x % 10; if (answer > INT_MAX || answer < INT_MIN) return 0; x /= 10; } return (int)answer; }
把正負判斷用long的截斷代替
推薦閱讀:
※[leetcode algorithms]題目17
※[leetcode algorithms]題目19
※[leetcode algorithms]題目5
※008 String to Integer (atoi)[M]