zoukankan      html  css  js  c++  java
  • OJ练习1——T168

    【LeetCode】Excel sheet column title

    输入非负整数n,输出以下格式:

    1 -> A

    2 -> B

    ......

    26 -> Z

    27 -> AA

    28 -> AB

    [分析]实质是将十进制转换为26进制。应该想到用string的+运算,可以连接字符。利用函数reverse(result.begin(),result.end())输出。

    对c++语言不熟悉,一开始的做法如下:

    class Solution {
    public:
        string convertToTitle(int n) {
        int i,p,q;
    	vector<char>vec;
    	for(i=0;i<n;i++){
    		cout<<i+1<<" "<<"->"<<" ";
    		p=i/26;
    		q=i%26;
    		vec.push_back(q+65);
    		while(p>0){
    			q=p%26;
    			p=p/26;
    			vec.push_back(q+64);
    			}
    		vector<char>::size_type r=vec.size()-1;	
    		while(r>=0&&r<n){
    			cout<<vec[r];
    			r--;
    		}	
    		cout<<endl;
    		vec.clear();
    	}  
        }
    };
    

     出现Runtime Error,不能通过。

    【错因】

    1.OJ平台需要封装成一个类的方法,不应该用for循环打印输出。

    2.程序本身有bug,10进制最小数是0,应该对应26进制最小数A,但是题目要求1对应A,那么每个n都应该减去1才能得出正确结果。

    3.类中已经提示返回的是string类型,不应该用vector<char>变量。

    正确做法是:

    class Solution {
    public:
        string convertToTitle(int n) {
            if(n < 1)
                return "";
            else
            {
                string result = "";
                while(n)
                {//get every letter in n from right to left
                    n --;
                    char c = n%26 + 'A';
                    result += c;
                    n /= 26;
                }
                reverse(result.begin(), result.end());
                return result;
            }
        }
    };
    

     经验证,用string类型的push_back(28ms)要比+运算(4ms)更耗费时间。

  • 相关阅读:
    static作用(1)
    Android开发之事件
    安卓开发之intent
    字符串去空
    字符串自实现(一)(mystrcpy,mystrcat,mystrcmp)
    Gin框架介绍及使用
    django model fake
    CentOS7 永久修改系统时间
    ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
    linux安装mysqlclient库
  • 原文地址:https://www.cnblogs.com/ketchups-notes/p/4199655.html
Copyright © 2011-2022 走看看