今天的題目比較難理解。

來源:互聯網
上載者:User

標籤:new   pow   今天   mat   .com   cti   tostring   closed   字串轉換   

 

(1)String to Integer (atoi)

解題思路:

實現atoi函數,將字串轉換成整型數。題目要求:

1. 首先需要丟棄字串前面的空格;(trim函數)

2. 然後可能有加號或減號(注意只取一個,如果有多個加號或減號,那麼說這個字串是無法轉換的,返回0。比如測試案例裡就有個“+-2”);

3. 字串可以包含0~9以外的字元,如果遇到非數字字元,那麼只取該字元之前的部分,如“-00123a66”返回為“-123”;

4. 如果超出int的範圍,返回邊界值(2147483647或-2147483648)。

代碼如下:

 1 public class Solution { 2     public int myAtoi(String str) {   3         // 1. null or empty string   4         if (str == null) { 5             return 0;   6         }   7          8         // 2. whitespaces   9         str = str.trim();  10         if (str.length() == 0) {11             return 0;12         } 13         14         // 3. +/- sign  15         int sign = 1;  16         int i = 0;  17         if (str.charAt(0) == ‘+‘) {  18             i++;  19         } else if (str.charAt(0) == ‘-‘) {  20             sign = -1;  21             i++;  22         }  23           24         // 4. calculate real value  25         double tmp = 0;  26         for ( ; i < str.length(); i++) {  27             int digit = str.charAt(i) - ‘0‘;  28             if (digit < 0 || digit > 9) {29                 break;  30             } 31             // 5. handle min & max  32             if (sign == 1) {  33                 tmp = 10*tmp + digit;  34                 if (tmp > Integer.MAX_VALUE) return Integer.MAX_VALUE;  35             } else {  36                 tmp = 10*tmp - digit;  37                 if (tmp < Integer.MIN_VALUE) return Integer.MIN_VALUE;  38             }  39         }  40           41         int ret = (int)tmp;  42         return ret;  43     }  44 }
View Code

(2)Rotate Function

解題思路:

F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1]F(k-1) = 0 * Bk-1[0] + 1 * Bk-1[1] + ... + (n-1) * Bk-1[n-1]       = 0 * Bk[1] + 1 * Bk[2] + ... + (n-2) * Bk[n-1] + (n-1) * Bk[0]

Then,

F(k) - F(k-1) = Bk[1] + Bk[2] + ... + Bk[n-1] + (1-n)Bk[0]              = (Bk[0] + ... + Bk[n-1]) - nBk[0]              = sum - nBk[0]

Thus,

F(k) = F(k-1) + sum - nBk[0]

What is Bk[0]?

k = 0; B[0] = A[0];k = 1; B[0] = A[len-1];k = 2; B[0] = A[len-2];
故可以先求出f[0]和sum,然後利用公式逐步求F[1],F[2]...並比較大小選取最大值。
代碼如下:

 1 public class Solution { 2     public int maxRotateFunction(int[] A) { 3         int allSum = 0;//所有數字之和 4         int len = A.length;//數組長度 5         int F = 0; 6         for (int i = 0; i < len; i++) { 7             F += i * A[i];//F[0] 8             allSum += A[i]; 9         }10         int max = F;11         for (int i = len - 1; i >= 1; i--) {12             F = F + allSum - len * A[i];//F[1],F[2],...13             max = Math.max(F, max);//找出最大值14         }15         return max; 16     }17 }
View Code

(3)Add Binary

解題思路:

從末尾依次對應相加來求,轉成int中的相加會使代碼比較簡潔,因為可以用/和%來分別求出進位和當前往結果中添加的位。然後,把較長的字串剩下的部分和進位相加放入結果。最後,還要判斷進位此時是否為1,如果為1,則需要再往結果中添加1,否則返回結果。

代碼一如下:較為簡潔

public class Solution {    public String addBinary(String a, String b) {        StringBuilder sb = new StringBuilder();        int i = a.length() - 1, j = b.length() -1, carry = 0;//carry進位標誌位        while (i >= 0 || j >= 0) {            int sum = carry;            if (j >= 0) sum += b.charAt(j--) - ‘0‘;            if (i >= 0) sum += a.charAt(i--) - ‘0‘;            sb.append(sum % 2);            carry = sum / 2;        }        if (carry != 0) sb.append(carry);        return sb.reverse().toString();    }}
View Code

代碼二:

 1 public class Solution { 2     public String addBinary(String a, String b) { 3         if(a.length() < b.length()){ 4             String tmp = a; 5             a = b; 6             b = tmp; 7         } 8          9         int pa = a.length()-1;10         int pb = b.length()-1;11         int carries = 0;12         String rst = "";13         14         while(pb >= 0){15             int sum = (int)(a.charAt(pa) - ‘0‘) + (int)(b.charAt(pb) - ‘0‘) + carries;16             rst = String.valueOf(sum % 2) + rst;17             carries = sum / 2;18             pa --;19             pb --;20         }21         22         while(pa >= 0){23             int sum = (int)(a.charAt(pa) - ‘0‘) + carries;24             rst = String.valueOf(sum % 2) + rst;25             carries = sum / 2;26             pa --;27         }       28         29         if (carries == 1)30             rst = "1" + rst;31         return rst;32     }33 }
View Code

(4)Nth Digit

解題思路:

 * 這裡首先分析一下位元和規律 * 個位元:1-9,一共9個,共計9個數字 * 2位元:10-99,一共90個,共計180個數字 * 3位元:100-999,一共900個,共計270個數字 * 4位元,1000-9999,一共9000個,共計36000個數字 * 以此類推, * 這樣我們就可以首先定位到是哪個數,再找到其對應的數字

代碼如下:

 1 public class Solution { 2     public int findNthDigit(int n) { 3         //小心溢出 4         int digitType = 1; 5         long digitNum = 9; 6         //定位到是幾位元 7         while(n > digitNum * digitType){ 8             n -= (int) digitNum * digitType ; 9             digitType++;//幾位元10             digitNum *= 10;11         }12         //定位到是這些幾位元裡面的第幾個的第幾位13         int indexInSubRange = (n -1) / digitType;//第幾個14         int indexInNum = (n -1) % digitType;//第幾位15         //還原數字16         int num = (int)Math.pow(10,digitType - 1) + indexInSubRange ;17         int result = Integer.parseInt((""+num).charAt(indexInNum)+"");18         return result;19     }20 }
View Code

注意:用(n-1)/digitType的原因,因為後面還原數位時候使用10的冪(10,100,...),但前面其實只有(9,99,...)個數,所有要先減一。

 

今天的題目比較難理解。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.