欧拉计划第42题 统计三角形单词个数

9 篇文章 0 订阅

欧拉计划第42题 统计三角形单词个数

题目:定义三角形数序列中第 n 项:tn=n(n+1)/2
这样得到前十个三角形数是:1, 3, 6, 10, 15, 21, 28, 36, 45, 55, … 把一个单词中每个字母在字母表中的位置值加起来('A’的位置值为 1,'Z’的位置值为 26),
可以将一个单词转换为一个数。

例如:单词 SKY 的值为 19 + 11 + 25 = 55 = t10 (其中’S’的位置值为 19,'K’的位置值为 11, 'Y’的位置值为 25)
如果单词的值是一个三角形数,则称该单词为三角形单词,例如 SKY 就是一个三角形单词。
p042_words.txt 是一个 16K 的文本文件,包含将近两千个常用英语单词。在这个文件中,一
共有多少个三角形词?
答案:162

public static int num(String str){  //一个单词转换为一个数
        int sum=0;
        for(int i=0;i<str.length();i++){
            char c=str.charAt(i);
            int a=c-'A'+1;
            sum+=a;
        }
        return sum;
    }

    public static boolean yesorno(int n){//判断是否为三角形数
        int s=n*2;
        if(n==1) return true;
        int i=1;
        for(;i*(i+1)<=s;i++);
        if(i*(i-1)==s) return true;
        return false;
    }
    public static void main(String[] args) throws FileNotFoundException {
        int nnum=0;//用来记录三角形数的个数
        ArrayList<String> nameList = new ArrayList<>();
        BufferedReader br=new BufferedReader(new FileReader(new File("E:\\project\\p042_words.txt")));
        //用来存放数字的txt文件
        try {
            String textLine="";
            String  str="";
            while((textLine = br.readLine())!=null){//读取文件,循环条件为行不为空
                str+=textLine;
            }

            String[] numList=str.split("\"");
            for(int i=numList.length-1;i>=0;i-=2){  //奇位数都是",",偶位数都是名字
                nameList.add(numList[i]);
            }
            Collections.sort(nameList);
            for(int i=0;i<nameList.size();i++){
               int n=num(nameList.get(i));
               if(yesorno(n))
                   nnum++;
            }
            System.out.println(nnum);
            br.close();
        } catch (IOException e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值