題目1:迴文數字猜想
給出一個數字N,如68,定義它的逆數爲86,那麼經過68+86=154,154+451=605,605+506=1111這樣幾次操作後,可以得到迴文數字1111。現在需要判斷經過7次操作是否可以得到迴文,如果能,輸出迴文,如果不能輸出0。思路:拆分各個位數並逆序相加,對和數判斷迴文。
(數字與逆序相加,如果對應位置相加不產生進位,那麼結果肯定是迴文;產生進位的有可能是迴文,如605+506)
- package tongji.edu.main;
- import java.util.Scanner;
- public class MainHuiwen {
- public static void main(String[] args) {
- @SuppressWarnings("resource")
- int n = new Scanner(System.in).nextInt(); //獲取輸入數字
- int hui = huiWen(n);
- System.out.println(hui);
- }
- /**
- * 七次操作後判斷是否是迴文
- */
- private static int huiWen(int n) {
- for (int i = 0; i < 7; i++)
- n = n + reverseNum(n);
- if (n == reverseNum(n))
- return n;
- else
- return 0;
- }
- /**
- * 對數字進行反轉
- */
- private static int reverseNum(int n) {
- return Integer.valueOf(new StringBuffer(String.valueOf(n)).reverse().toString()).intValue();
- }
- }
題目2:找出大串中指定子串個數並刪除
找出大串中指定子串個數,並刪除,返回最終的字符串和所包含子串的數量
- package study.edu.main;
- public class MainDeleteSubString{
- public static void main(String[] args) {
- String str = "123abc12de234fg1hi34j123k";
- String subStr = "1";
- String[] strArray = str.split(subStr);
- String StrDelsub="";
- int count=0;
- for(String temp:strArray){
- StrDelsub+=temp;
- if(!temp.equals("")) //split分割字符串,如果分隔符在首部,分割後的字符串會出現一個空字符串
- count++;
- }
- System.out.println("The number of sub str is :" + count);
- System.out.println("The result string is: " + StrDelsub);
- }
- }
找出字符串中指定子串個數的另一種方法:
- package study.edu.main;
- public class MainSubString {
- public static void main(String[] args) {
- String str = "123abc12de234fg1hi34j123k";
- String subStr = "12";
- int n = deleteSub(str, subStr);
- System.out.println("The number of sub str is :" + n);
- }
- /**
- * 利用String的indexOf()函數來判斷長串中指定字串個數
- */
- private static int deleteSub(String str, String subStr) {
- int count = 0;
- String lstr = str.toString();
- int i = lstr.indexOf(subStr);
- int now = 0;
- while (i != -1 && i < str.length()) {
- now = lstr.indexOf(subStr, i);
- if (now != -1) {
- count++;
- i = now + subStr.length();
- } else {
- i = now;
- }
- }
- return count;
- }
- }
題目3:約瑟夫環問題
有n 個人圍城一圈每次從1數起數到3就把那個人提出圈子,最後只保留一個人。
輸入: 輸入人數字符串
輸出:把最後一個人所保留位置返回出來。
比如你輸入11 的話即有11個人 [1,2,3,4,5,6,7,8,9,10,11] 。返回的是7.
如果輸入"1a" 的話,返回的是"0"
- package study.edu.main;
- import java.util.LinkedList;
- import java.util.List;
- import java.util.Scanner;
- public class MainLink {
- public static void main(String[] args) {
- @SuppressWarnings("resource")
- Scanner scanner = new Scanner(System.in);
- int n = 0;
- try {
- n = scanner.nextInt();
- if(n<1)
- throw new Exception("wrong input");
- List<Integer> peopleLink = new LinkedList<Integer>();
- for (int i = 1; i <= n; i++) {
- peopleLink.add(i);
- }
- int count = 0;
- while (peopleLink.size() > 1) {
- for (int i = 0; i < peopleLink.size(); i++) {
- count++;
- if (count == 3) {
- peopleLink.remove(i); // 出圈
- count = 0;
- i--; // 索引回退1步
- }
- }
- }
- System.out.println(peopleLink.get(0));
- } catch (Exception e) {
- System.out.println(0);
- return;
- }
- }
- }