--- tags: Cmoney_Java題目 --- Java_Cmoney_ft9108_找出連續正整數 ===  1.主程式 --- **使用迴圈找最長正整數序列** 1. 變數 1. 最長 : maxCount 2. 最長從哪開始 : maxIndex 3. 長度 : count 4. 從哪開始 : curIndex 2. 如果是 > 0 , count++ , 此外如果是 count == 1 , 代表這個數列從這開始 , curIndex = i 3. 否則 count = 0 , 重新計算長度 4. 如果現在長度( count ) > maxCount,將 maxCount 和 maxIndex 更新 **計算總和** 1. 加總是從 maxIndex 到 maxIndex + maxCount - 1, 所以是`int i = maxIndex; i < maxIndex + maxCount;` ```java= import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); /* import numbers */ int[] numbers = new int[n]; for (int i = 0; i < n; i++) { numbers[i] = sc.nextInt(); } /* find longest sequence of positive integers in an array */ int maxCount = 0, maxIndex = 0, count = 0, curIndex = 0; for (int i = 0; i < numbers.length; i++) { if (numbers[i] > 0) { count++; if (count == 1) curIndex = i; } else { count = 0; } if (count > maxCount) { maxCount = count; maxIndex = curIndex; } } /* calculate sum */ int sum = 0; if (maxCount == 0) System.out.println(-1); else { for (int i = maxIndex; i < maxIndex + maxCount; i++) { sum += numbers[i]; } System.out.println(sum); } } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up