基本算法题汇

来源:互联网 发布:学习软件 编辑:程序博客网 时间:2024/05/16 05:07

原文地址:点击打开链接

1.一道简单16进制加密算法

Java代码  收藏代码
  1. /** 
  2.  * 简单加密解密算法 
  3.  * 任意十六进制字符ascii转换,转换规则: 
  4.  * 当前index位置的数加上index,如果结果超出F则从0重新开始循环 
  5.  * 比如: "3A4E"应该被转换为"3B61" 
  6.  *   3在0位置,所以保持不变, 
  7.  *   A在1位置,转化为B, 
  8.  *   4在2位置,转化为6, 
  9.  *   E在3位置,转化为1, 
  10.  * 然后倒转字符,比如"3B61"转换为"16B3" 
  11.  */  
  12. public class Encryption {  
  13.     public static void main(String[] args) {  
  14.         System.out.println(Decrypt2(encrypt2("3A4E46ABAE829")));    
  15.         System.out.println(encrypt2("3A4E"));    
  16.         System.out.println(Decrypt2("16B3"));  
  17.     }  
  18.       
  19.     //encrypt 加密  
  20.     public static String encrypt2(String hexStr){  
  21.         String template = "0123456789ABCDEF";  
  22.         int len = hexStr.length();  
  23.         char[] result = new char[len];  
  24.         int index = 0;  
  25.         int ch = 0;  
  26.         for(int i=0;i<len;i++){  
  27.             ch = hexStr.charAt(i);  
  28.             index = (i + template.indexOf(ch))%16;  
  29.             result[i] = template.charAt(index);  
  30.         }  
  31.         result = reverse(result);  
  32.         return new String(result);  
  33.     }  
  34.       
  35.     //Decrypt 解密  
  36.     public static String Decrypt2(String hexStr){  
  37.         String template = "FEDCBA9876543210";  
  38.         char[] argStr = hexStr.toCharArray();  
  39.         argStr = reverse(argStr);  
  40.   
  41.         char[] result = new char[argStr.length];  
  42.         int index = 0;  
  43.         for(int i=0;i<argStr.length;i++){  
  44.             index = (i + template.indexOf(argStr[i]))%16;  
  45.             result[i] = template.charAt(index);  
  46.         }  
  47.         return new String(result);  
  48.     }  
  49.       
  50.     //reverse the char array  
  51.     public static char[] reverse(char[] chs){  
  52.         char temp;  
  53.         for(int i=0;i<chs.length/2;i++){  
  54.             temp = chs[i];  
  55.             chs[i] = chs[chs.length-1-i];  
  56.             chs[chs.length-1-i] = temp;  
  57.         }  
  58.         return chs;  
  59.     }  
  60. }  



2.上机试题三则
Java代码  收藏代码
  1. public class HaweiQuestion {  
  2.     public static void main(String[] args) {  
  3.         HaweiQuestion q = new HaweiQuestion();  
  4.         int[] input = {361978};   
  5.         int[] output = new int[input.length];  
  6.         q.sort(input, input.length, output);  
  7.         for(int i=0;i<input.length;i++){  
  8.             System.out.print(output[i]+" ");  
  9.         }  
  10.         System.out.println();  
  11.         int[] task = {0301551803001704099};  
  12.         int[] system_task = new int[task.length];  
  13.         int[] user_task = new int[task.length];  
  14.         q.scheduler(task, task.length, system_task, user_task);  
  15.           
  16.     }  
  17.       
  18.     /** 
  19.      * 选秀节目打分,分为专家评委和大众评委,score[] 数组里面存储每个评委打的分数, 
  20.      * judge_type[] 里存储与 score[] 数组对应的评委类别,judge_type[i] == 1,表示专家评委, 
  21.      * judge_type[i] == 2,表示大众评委,n表示评委总数。 
  22.      * 打分规则如下:专家评委和大众评委的分数先分别取一个平均分(平均分取整), 
  23.      * 然后,总分 = 专家评委平均分 * 0.6 + 大众评委 * 0.4,总分取整。如果没有大众评委, 
  24.      * 则 总分 = 专家评委平均分,总分取整。函数最终返回选手得分。 
  25.      */  
  26.     public int cal_score(int score[], int judge_type[], int n)  {  
  27.         int proNum=0;  
  28.         int peoNum=0;  
  29.         int total=0;  
  30.         int peoCount=0;  
  31.         for(int i=0;i<n;i++){  
  32.             if(judge_type[i]==1){  
  33.                 proNum += score[i];  
  34.             }else{  
  35.                 peoNum += score[i];  
  36.                 peoCount++;  
  37.             }  
  38.         }  
  39.         if(peoCount!=0)  
  40.             total = (int)(proNum * 0.6 + peoNum * 0.4);  
  41.         else  
  42.             total = proNum / n ;  
  43.         return total;  
  44.     }  
  45.       
  46.       
  47.     /** 
  48.      * 给定一个数组input[] ,如果数组长度n为奇数, 
  49.      * 则将数组中最大的元素放到 output[] 数组最中间的位置, 
  50.      * 如果数组长度n为偶数,则将数组中最大的元素放到 output[] 数组中间两个位置偏右的那个位置上, 
  51.      * 然后再按从大到小的顺序,依次在第一个位置的两边,按照一左一右的顺序,依次存放剩下的数。 
  52.      * 例如:input[] = {3, 6, 1, 9, 7} output[] = {3, 7, 9, 6, 1};  
  53.      * input[] = {3, 6, 1, 9, 7, 8} output[] = {1, 6, 8, 9, 7, 3} 
  54.      */  
  55.      public void sort(int input[], int n, int output[]){  
  56.          //首先按从大到小的顺序排列input  
  57.          for(int i=0; i < n;i++){  
  58.              for(int j = i;j > 0;j--){  
  59.                  if(input[j] > input[j-1]){  //大数上浮  
  60.                      swap(input,j,j-1);  
  61.                  }  
  62.              }  
  63.          }  
  64.   
  65.         int count = 0;  
  66.         for (int i = n / 2, j = n / 2; i >= 0 && j < n; i--, j++) {  
  67.             if (i == j) {  
  68.                 output[i] = input[count++];  
  69.             } else {  
  70.                 output[i] = input[count++];  
  71.                 output[j] = input[count++];  
  72.             }  
  73.         }  
  74.         if(n%2 == 0){   //偶数还有一个值  
  75.             output[0] = input[count];  
  76.         }  
  77.            
  78.      }  
  79.   
  80.     private void swap(int[] input, int j, int i) {  
  81.         int temp = input[j];  
  82.         input[j] = input[j-1];  
  83.         input[j-1] = temp;  
  84.           
  85.     }  
  86.       
  87.       
  88.     /** 
  89.      * 操作系统任务调度问题。操作系统任务分为系统任务和用户任务两种。 
  90.      * 其中,系统任务的优先级 < 50,用户任务的优先级 >= 50且 <= 255。 
  91.      * 优先级大于255的为非法任务,应予以剔除。 
  92.      * 现有一任务队列task[],长度为n,task中的元素值表示任务的优先级,数值越小,优先级越高。 
  93.      * 函数scheduler实现如下功能,将task[] 中的任务按照系统任务、用户任务依次存放到 system_task[]数组和  
  94.      * user_task[] 数组中(数组中元素的值是任务在task[] 数组中的下标), 
  95.      * 并且优先级高的任务排在前面,优先级相同的任务按照入队顺序排列(即先入队的任务排在前面), 
  96.      * 数组元素为-1表示结束。 
  97.      * 例如:task[] = {0, 30, 155, 1, 80, 300, 170, 40, 99}  
  98.      * system_task[] = {0, 3, 1, 7, -1} user_task[] = {4, 8, 2, 6, -1} 
  99.      */  
  100.     public void scheduler(int task[], int n, int system_task[], int user_task[]){  
  101.         int[] indexs = new int[n];  //用来保存下标  
  102.         for(int i=0;i<n;i++){    //初始化  
  103.             indexs[i] = i ;  
  104.         }  
  105.         //按从小到大的顺序排列task  
  106.          for(int i=0; i < n;i++){  
  107.              for(int j = i;j > 0;j--){  
  108.                  if(task[j] < task[j-1]){    //小数上浮,相等不交换  
  109.                      swap(task,j,j-1);  
  110.                      swap(indexs,j,j-1);    //同时交换下标  
  111.                  }  
  112.              }  
  113.          }  
  114.          int sysPoint = 0;  
  115.          int userPoint = 0;  
  116.          for(int i=0;i<n;i++){  
  117.              if(task[i] < 50){  
  118.                  system_task[sysPoint++] = indexs[i];  
  119.              }else if(task[i]<=255){  
  120.                  user_task[userPoint++] = indexs[i];  
  121.              }else{  
  122.                  //do nothing  
  123.              }  
  124.          }  
  125.     }  
  126. }  



3.将1-9组成三个特殊三位数
Java代码  收藏代码
  1. /* 
  2.  *  将1-9九个数字组合成三个三位数。 
  3.  *  要求1-9每个数字只使用一次,且第二个数是第一个数的两倍,第三个数是第一个数的三倍。 
  4.  *  符合条件的数有几组?将他们打印出来。 
  5.  * */  
  6. public class FindGroup {  
  7.     public static void main(String[] args) {  
  8.         int maxNumber = 987/3;   //不重复最大数为987  
  9.         int count = 0;  
  10.         for(int i=123;i<maxNumber;i++){  
  11.             if(isRepeat(i+""+i*2+""+i*3)){   //无重复  
  12.                 count++;  
  13.                 System.out.println(i+" "+i*2+" "+i*3);  
  14.             }  
  15.         }  
  16.     }  
  17.       
  18.     public static boolean isRepeat(String str){       //判断是否有重复数字  
  19.         char[] chs = str.toCharArray();  
  20.         String reserve = "";  
  21.         for(int i=0;i<chs.length;i++){  
  22.             if(reserve.indexOf(chs[i])==-1){  
  23.                 reserve+=chs[i];  
  24.             }  
  25.         }  
  26.         return chs.length==reserve.length()?true:false;  
  27.     }  
  28. }  



4.超大数相加
Java代码  收藏代码
  1. public class AddBigNumber {  
  2.     public static void main(String[] args) {  
  3.         String data1 = "123456";  
  4.         String data2 = "22";  
  5.         String result = add(data1,data2);  
  6.         System.out.println(result);  
  7.   
  8.     }  
  9.   
  10.     public static String add(String data1, String data2) {  
  11.         int store = 0;  
  12.         int len1 = data1.length();  
  13.         int len2 = data2.length();  
  14.         StringBuffer sb = new StringBuffer();  
  15.         for(int i=0;i<(len1>len2?len1:len2);i++){  
  16.             int d1 = getLowerNumber(i,data1);  
  17.             int d2 = getLowerNumber(i,data2);  
  18.             int sum = d1 + d2 + store;  
  19.               
  20.             store = sum/10;       //有进位就存下来  
  21.             sb.append(sum%10);  
  22.         }  
  23.         if(store!=0)sb.append(store);     //考虑最高位进位  
  24.         return sb.reverse().toString();  
  25.     }  
  26.       
  27.     public static int getLowerNumber(int i,String str){  
  28.         if(i>=str.length())return 0;  
  29.         String s = str.charAt(str.length()-1-i)+"";  
  30.         return Integer.parseInt(s);  
  31.     }  
  32. }  



5.求喝饮料数与求日期
Java代码  收藏代码
  1. package com.algorithm;  
  2.   
  3. /** 
  4.  * @author  
  5.  * http://topic.csdn.net/u/20111012/20/1c402221-028c-4920-b2fc-0b63b839d256.html?38410 
  6.  */  
  7. public class BottleDay {  
  8.     /** 
  9.      * 20块钱,1块钱1瓶,两个空瓶子可以换一瓶,问最多可以喝几瓶? 
  10.      */  
  11.     public static void maxDrink(){  
  12.         int sum = 20;  
  13.         int bottle = sum;  
  14.         while (bottle > 1) {  
  15.             System.out.println(bottle+" "+bottle/2);  
  16.             sum += bottle/2;  
  17.             bottle = bottle%2 + bottle/2;  
  18.         }  
  19.         System.out.println(sum);  
  20.     }  
  21.       
  22.       
  23.     /** 
  24.      * 有一名员工发现日历已经7天没有翻了, 
  25.      * 于是他连着翻了7页,7天的总和刚好是138,问这一天是几号? 
  26.      */  
  27.     public static void getSpecialDay() {  
  28.         int[] end = { 28293031 };     //可能的月末最後一天  
  29.         int days = 138;  
  30.         int count = 0;  
  31.         int day;   
  32.         int max;  
  33.         boolean found = false;  //标志位  
  34.         for (int i = 0; i < end.length; i++) {  
  35.             max = end[i] + 7;   //7号  
  36.             day = 1;  
  37.             while (max > 0) {  
  38.                 count = 0;  
  39.                 for (int j = day; j < day + 7; j++) {  
  40.                     if (j > end[i]) {  
  41.                         count += j % end[i];  
  42.                     } else {  
  43.                         count += j;  
  44.                     }  
  45.                 }  
  46.                 if (count == days) {  
  47.                     found = true;  
  48.                     for (int j = day; j < day + 7; j++) {  
  49.                         System.out.printf("%d, ", j > end[i] ? j % end[i] : j);  
  50.                     }  
  51.                     break;  
  52.                 }  
  53.                 day++;  
  54.                 max--;  
  55.             }  
  56.             if (found) {  
  57.                 System.out.printf("------end=%d\n", end[i]);  
  58.                 break;  
  59.             }  
  60.         }  
  61.         if (!found) {  
  62.             System.out.println("error");  
  63.         }  
  64.     }  
  65.       
  66.     public static void main(String[] args) {  
  67.         maxDrink();  
  68.         System.out.println("--------");  
  69.         getSpecialDay();  
  70.     }  
  71. }  


6.正则表达式按要求切割代码
文件名:test.txt,这是要切割的代码
Java代码  收藏代码
  1. #include<iostream>  
  2. int main()  
  3. {  
  4.     int c[20];  
  5.     int a=5;  
  6.     int b=a+12;  
  7.     for(int i=0;i<=10;i++)  
  8.     {  
  9.         c[i]=i;    
  10.     }  
  11.     return 0;  
  12. }  

算法如下
Java代码  收藏代码
  1. package com.algorithm;  
  2.   
  3.   
  4. import java.io.BufferedReader;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.IOException;  
  8. import java.io.InputStreamReader;  
  9. import java.util.ArrayList;  
  10. import java.util.regex.Matcher;  
  11. import java.util.regex.Pattern;  
  12.   
  13. /** 
  14.  * author:yunan 
  15.  */  
  16. public class SpiltCode {  
  17.     //你要保留的连续的字符  
  18.     private String[] codes = {"==","++","--",">=","+=","<="};  //等等..  
  19.     ArrayList<String> saveTable = new ArrayList<String>();  //保存所有切割出来的串  
  20.       
  21.     public static void main(String[] args) {  
  22.         new SpiltCode().spiltCode();  
  23.     }  
  24.       
  25.     private BufferedReader getBuffreader(String path){  
  26.         File file = new File(path);  
  27.         FileInputStream in;  
  28.         BufferedReader reader=null;  
  29.         try {  
  30.             in = new FileInputStream(file);  
  31.             reader = new BufferedReader(new InputStreamReader(in));  
  32.         } catch (Exception e) {   
  33.             e.printStackTrace();  
  34.         }  
  35.         return reader;  
  36.     }  
  37.       
  38.     public  void spiltCode(){  
  39.         BufferedReader reader = getBuffreader("test.txt");  
  40.         String regex = "\\w+|\\p{Punct}";   //这个可以把单词和一个一个特殊字符全切出来  
  41.         Pattern p = Pattern.compile(regex);  
  42.         Matcher m = null;  
  43.         String line = null;  
  44.         String pre = "";    //上一个匹配的串  
  45.         int index = 0;  
  46.         try {  
  47.             while((line=reader.readLine())!=null){  
  48.                 m = p.matcher(line);  
  49.                 while(m.find()){  
  50.                     String chars = m.group();  
  51.                     if(isInCodes(pre+chars)){   
  52.                         saveTable.set(--index, pre+chars);  
  53.                     }else{   
  54.                         saveTable.add(chars);  
  55.                     }  
  56.                     pre = chars;  
  57.                     index++;  
  58.                 }  
  59.             }  
  60.         } catch (IOException e) {  
  61.             e.printStackTrace();  
  62.         }  
  63.         printTable();   //打印  
  64.     }  
  65.       
  66.     private boolean isInCodes(String code){  
  67.         for(int i=0;i<codes.length;i++){  
  68.             if(codes[i].equals(code)){  
  69.                 return true;  
  70.             }  
  71.         }  
  72.         return false;  
  73.     }  
  74.       
  75.     private void printTable(){  
  76.         for(String sav:saveTable){  
  77.             System.out.println(sav);  
  78.         }  
  79.     }  
  80. }  
  81. 结果如下:  
  82. <pre name="code" class="java">#  
  83. include  
  84. <  
  85. iostream  
  86. >  
  87. int  
  88. main  
  89. (  
  90. )  
  91. {  
  92. int  
  93. c  
  94. [  
  95. 20  
  96. ]  
  97. ;  
  98. int  
  99. a  
  100. =  
  101. 5  
  102. ;  
  103. int  
  104. b  
  105. =  
  106. a  
  107. +  
  108. 12  
  109. ;  
  110. for  
  111. (  
  112. int  
  113. i  
  114. =  
  115. 0  
  116. ;  
  117. i  
  118. <=  
  119. 10  
  120. ;  
  121. i  
  122. ++  
  123. )  
  124. {  
  125. c  
  126. [  
  127. i  
  128. ]  
  129. =  
  130. i  
  131. ;  
  132. }  
  133. return  
  134. 0  
  135. ;  
  136. }  
  137.   
  138. </pre>  
  139. <br>  



7.超大数相乘的两种方法
Java代码  收藏代码
  1. //方法一  
  2. public static void testMul()  {  
  3.         String p1 = "123456789012345678901234123456789012345678901234";// "123456789012345678901234";  
  4.         String p2 = "987654321098765432109876543210987654123456789012345678901234";// "987654321098765432109876543210987654";  
  5.         int ASCII = 48;  
  6.         char[] result = new char[p1.length() + p2.length()];  
  7.         for (int i = 0; i < result.length; i++) {  
  8.             result[i] = '0';  
  9.         }  
  10.         char ctemp = ' ';  
  11.         char[] pc1 = p1.toCharArray();  
  12.         for (int i = 0; i < pc1.length / 2; i++) {   //交换位置,如45689变98654  
  13.             ctemp = pc1[i];  
  14.             pc1[i] = pc1[pc1.length - 1 - i];  
  15.             pc1[pc1.length - 1 - i] = ctemp;  
  16.         }  
  17.           
  18.         char[] pc2 = p2.toCharArray();  
  19.         for (int i = 0; i < pc2.length / 2; i++) {  
  20.             ctemp = pc2[i];  
  21.             pc2[i] = pc2[pc2.length - 1 - i];  
  22.             pc2[pc2.length - 1 - i] = ctemp;  
  23.         }  
  24.         int temp = 0;// 临时结果  
  25.         int step = 0;// 进位  
  26.         int time = 0;// 次数  
  27.         int bit = 0;// 位数  
  28.         for (char c1 : pc1) {   //021  
  29.             time = bit;  
  30.             for (char c2 : pc2) {   //654  
  31.                 temp = (c1 - ASCII) * (c2 - ASCII); //0  
  32.                 temp = temp + result[time] - ASCII; //0  
  33.                 if (temp > 9) {// 进位  
  34.                     int i = 0;  
  35.                     do {  
  36.                         result[time + i] = (char) (temp % 10 + ASCII);  
  37.                         step = (temp - temp % 10) / 10;  
  38.                         i++;  
  39.                         temp = result[time + i] - ASCII + step;  
  40.                     } while (temp > 9);  
  41.                     result[time + i] = (char) (temp + ASCII);  
  42.                 } else {  
  43.                     result[time] = (char) (temp + ASCII); //result[0] = '0'  
  44.                 }  
  45.                 time++;  
  46.             }  
  47.             bit++;  
  48.         }  
  49.         System.out.println("##############################");  
  50.         System.out.print(p1 + " x " + p2 + " = ");  
  51.         for (int i = result.length - 1; i >= 0; i--) {  
  52.             System.out.print(result[i]);  
  53.         }  
  54.         System.out.println();  
  55.         System.out.println("##############################");  
  56.     }  
  57.       
  58.       
  59.       
  60.     //方法二  
  61.     public static void bigNumberMulti(){  
  62.         String num1 = "123456789012345678901234123456789012345678901234";  
  63.         String num2 = "987654321098765432109876543210987654123456789012345678901234";  
  64.           
  65.         char[] cp1 = num1.toCharArray();  
  66.         char[] cp2 = num2.toCharArray();  
  67.           
  68.         char[] result = new char[cp1.length+cp2.length];   //用于存储每位的值  
  69.           
  70.         //矩阵存储计算的值  
  71.         int sum = cp1.length+cp2.length;    //竖排总数  
  72.         char[][] caculate = new char[cp1.length][sum];    
  73.         for(int i=0;i<caculate.length;i++){  
  74.             for(int j=0;j<caculate[0].length;j++){  
  75.                 caculate[i][j] = ' ';  
  76.             }  
  77.         }  
  78.           
  79.         int bit = 0;   //位数  
  80.         int level = 0;  //层数  
  81.         int temp = 0;  //临时存储的数据  
  82.         int ASIIC0 = 48;  //0的asiic码值  
  83.         int carry = 0//进位  
  84.         for(int i=cp1.length-1;i>=0;i--){    //9  
  85.             bit = sum-1;      
  86.             for(int j=cp2.length-1;j>=0;j--){    //6  
  87.                 temp = (cp1[i]- ASIIC0) * (cp2[j]-ASIIC0) + carry;  
  88.                 carry = 0;  
  89.                 if(temp>9){  
  90.                     carry = temp / 10;  
  91.                     temp = temp % 10 ;  
  92.                 }  
  93.                 caculate[level][bit--] = (char) (temp + ASIIC0);  
  94.             }  
  95.             //如果最后一位还有进位  
  96.             if(carry>0){  
  97.                 caculate[level][bit] =  (char)(carry + ASIIC0);  
  98.                 carry=0;  
  99.             }  
  100.             sum--;  
  101.             level++;  
  102.         }  
  103.           
  104.         int carry2 = 0;  
  105.         for(int y=caculate[0].length-1;y>=0;y--){  
  106.             int value = 0;  
  107.             for(int x=0;x<caculate.length;x++){  
  108.                 if(caculate[x][y]>='0' && caculate[x][y]<='9'){  
  109.                     value += caculate[x][y] - ASIIC0;  
  110.                 }  
  111.             }  
  112.             value += carry2;  
  113.             carry2 = 0;  
  114.             if(value>9){  
  115.                 carry2 = value / 10;  
  116.                 value = value % 10;  
  117.             }  
  118.             result[y] = (char)(value + ASIIC0);  
  119.         }  
  120.         System.out.println(result);  
  121.           
  122.         System.out.println("====================用于显示=======================");  
  123.         for(int i=0;i<caculate.length;i++){  
  124.             for(int j=0;j<caculate[0].length;j++){  
  125.                 System.out.print(caculate[i][j]+" ");  
  126.             }  
  127.             System.out.println();  
  128.         }  
  129.         for(int i=0;i<caculate[0].length;i++){  
  130.             System.out.print("--");  
  131.         }  
  132.         System.out.println();  
  133.         for(char re:result){  
  134.             System.out.print(re+" ");  
  135.         }  
  136.           
  137.     } 
0 0
原创粉丝点击