zoukankan      html  css  js  c++  java
  • LeetCode题解之Add Strings

    1、题目描述

    2、问题分析

    直接按照加法运算规则运算即可,注意进位问题。

    3、代码

     1 string addStrings(string num1, string num2) {
     2         if( num1.empty() ) return num2;
     3         if( num2.empty() ) return num1;
     4         
     5         string::reverse_iterator it1 = num1.rbegin() ;
     6         string::reverse_iterator it2 = num2.rbegin() ;
     7         string s ;
     8         int up = 0;
     9         while( it1 != num1.rend() && it2 != num2.rend() ){
    10             int a = (*it1 - '0') + (*it2 - '0') + up ;
    11             if( a < 10 ){
    12                 s = std::to_string( a ) + s;
    13                 up = 0;
    14             }else{
    15                 s = std::to_string( a - 10 ) + s;
    16                 up = 1;
    17             }
    18             ++it1;
    19             ++it2;
    20         }
    21         
    22         while( it1 != num1.rend() ){
    23             if( *it1 - '0' + up  < 10 ){
    24                 s = std::to_string( *it1 - '0' + up )  + s;
    25                 up = 0;
    26             }else{
    27                 s = std::to_string( *it1 - '0' + up - 10 )  + s;
    28                 up = 1;
    29             }
    30             ++it1;
    31         }
    32         
    33         while( it2 != num2.rend() ){
    34             if( *it2 - '0' + up < 10 ){
    35                 s = std::to_string( *it2 - '0' + up ) + s;
    36                 up = 0;
    37             }else{
    38                 s = std::to_string( *it2 - '0' + up - 10 ) + s;
    39                 up = 1;
    40             }
    41             ++it2 ;
    42         }
    43         
    44         if( up == 1 ){
    45             s  = std::to_string(1) + s;
    46         }
    47         
    48         return s;
    49         
    50     }
    pp
  • 相关阅读:
    网络爬虫(抓取)正则表达式 (多线程协作)
    Asp.net 主题
    Asp.net 菜单控件
    CSS 布局Float 【4】
    CSS 布局Float 【3】
    CSS 布局Float 【2】
    CSS 布局Float 【1】
    CSS 布局Float 【0】
    Asp.Net 母版页
    Sql Server 远程过程调用失败
  • 原文地址:https://www.cnblogs.com/wangxiaoyong/p/9298614.html
Copyright © 2011-2022 走看看